【问题标题】:What is the difference between using System.Drawing.Size and $button.Top & $button.Left in Windows Forms?在 Windows 窗体中使用 System.Drawing.Size 和 $button.Top & $button.Left 有什么区别?
【发布时间】:2016-12-21 01:47:31
【问题描述】:

我一直在 Powershell 中设计一个 GUI(从没想过我会使用这句话),并且在查看不同的在线资源时,有不同的方法可以在表单中定位控制项。

当我第一次开始熟悉如何构建简单表单的基本框架时,它显示了这一点:

[System.Reflection.Assembly]::LoadWithPartialName('System.Windows.Forms')
$form = New-Object System.Windows.Forms.Form

$button = New-Object System.Windows.Forms.Button
$button.Top = 30
$button.Left = 30
$form.Controls.Add($button)

但是,环顾四周,我看到大多数地方都使用这种方法:

[System.Reflection.Assembly]::LoadWithPartialName('System.Windows.Forms')
[System.Reflection.Assembly]::LoadWithPartialName('System.Drawing')

$form = New-Object System.Windows.Forms.Form

$button = New-Object System.Windows.Forms.Button
$button.Location = New-Object System.Drawing.Size(30,30)
$form.Controls.Add($button)

它似乎完成了完全相同的事情。

做同一件事的不同方法使编程变得有趣(无论如何,对我来说)。我想知道的是,后者是否更普遍地被证明是有原因的,是否有原因。

谢谢。

【问题讨论】:

    标签: winforms powershell user-interface system.drawing


    【解决方案1】:

    是的,你是对的。最后是完全一样的。所有三个属性都派生自 system.windows.forms.control。


    微软的文档说:

    Control.Left:获取或设置控件左边缘与其容器客户区左边缘之间的距离(以像素为单位) [...] Left 属性值相当于控件的 Location 属性值的 Point.X 属性。

    Control.Top:获取或设置控件上边缘与其容器客户区上边缘之间的距离(以像素为单位)。 [...] Top 属性值等同于控件的 Location 属性值的 Point.Y 属性。


    这取决于您想在特定场景中使用什么。我看到的唯一真正的区别是,要设置 Location 您需要一个新对象(值类型)。对于仅设置顶部或左侧,您只需要一个 [int]。

    【讨论】:

    • 太棒了!看起来 System.Drawing.Size($control.Left, $control.Top) 很可能,但 Windows 倾向于保留冗余工具和方法以方便使用。
    猜你喜欢
    • 2014-07-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-10
    • 2010-10-27
    • 2015-09-03
    • 2011-02-02
    相关资源
    最近更新 更多