Malachilee
Malachilee

Reputation: 99

Is there a way to position a form in the same position on any size screen?

I'm trying to position a form in a specific spot on the screen when opening. I used Form1.Location = New Point(200, 1200) which worked on my screen but on another screen it placed the form outside the viewing area. Is there a way to check the screen size first and position the form with a percent of screen position? Something like this Me.Location = New Point(Height / 2, Width / 2) but not in the center?

Upvotes: 2

Views: 1655

Answers (2)

djv
djv

Reputation: 15774

Well it's actually quite simple. There is something built into the Form called System.Windows.Forms.StartPosition. This one line Me.StartPosition = FormStartPosition.CenterScreen must be put in the constructor.

Sub New()
    InitializeComponent()
    Me.StartPosition = FormStartPosition.CenterScreen
End Sub

If you are doing it manually, perhaps because you don't want to modify the constructor for any reason, here is code to use. I know you have accepted an answer but there is no My namespace in c# so I usually try to avoid it because I frequently switch between the languages. I know it's not a requirement but it's just a recommendation. Using System.Windows.Forms.Screen,

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    Dim x = CInt((Screen.PrimaryScreen.Bounds.Width - Me.Width) / 2)
    Dim y = CInt((Screen.PrimaryScreen.Bounds.Height - Me.Height) / 2)
    Me.Location = New System.Drawing.Point(x, y)
End Sub

Upvotes: 1

G3nt_M3caj
G3nt_M3caj

Reputation: 2685

Do you mean something like that?

Me.Location = New Point(CInt((My.Computer.Screen.WorkingArea.Width - Me.Width) * 0.5),
                        CInt((My.Computer.Screen.WorkingArea.Height - Me.Height) * 0.5))

Upvotes: 3

Related Questions