Search code examples
winformspowershelluser-interfacesystem.drawing

What is the difference between using System.Drawing.Size and $button.Top & $button.Left in Windows Forms?


I have been designing a GUI in Powershell (never thought I'd use that sentence) and, while looking at different sources online, there are different methods for positioning Control Items withing a form.

When I first starting familiarizing myself with the basic framework on how to build a simple form, it shows this:

[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)

However, looking around, I have seen most places use this method:

[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)

It appears to accomplish the exact same thing.

Different ways to do the same thing is what makes programming interesting (to me, anyway). What I would like to know is if there is a reason why the latter is more commonly demonstrated and if there is a reason why.

Thanks.


Solution

  • Yes you are right. At the end it is exactly the same. All three properties are derived from system.windows.forms.control.


    The documentation from Microsoft says:

    Control.Left: Gets or sets the distance, in pixels, between the left edge of the control and the left edge of its container's client area [...] The Left property value is equivalent to the Point.X property of the Location property value of the control.

    Control.Top: Gets or sets the distance, in pixels, between the top edge of the control and the top edge of its container's client area. [...] The Top property value is equivalent to the Point.Y property of the Location property value of the control.


    It's up to you what you'd like to use in a specific scenario. The only real difference I see, is that for setting the Location you need a new object (value type). For just setting top or left you only need an [int].