Tuesday, November 18, 2008

Setting Window / Form Position Programmatically

Level: Beginner

Knowledge Required:
Windows Forms

Description:
While working with Windows Forms we sometimes require to set the Window/Form Position manually before we show it. Consider the following code:
Dim frmNew as Form2
frmNew = New Form2()
frmNew.Location = New Point(10, 10)
frmNew.Show()

If we execute the above code, it is NOT sure that window will be displayed at 10, 10. Because we haven't set the StartPosition property. By default this property is equal to WindowsDefaultLocation that is why whenever we display the Form, Windows Operating system choose where to put it. And if we change Location after the frmNew.Show(), then our location will set.

To set the Location programmatically we should first set the StartPosition property as,

Dim frmNew as Form2
frmNew = New Form2()
frmNew.StartPosition = FormStartPosition.Manual
frmNew.Location = New Point(10, 10)
frmNew.Show()