I’ve often found it necessary to center a form on my screen using the pure code, but it’s not as easy as Me.center in Visual Basic or this.center() in C# so I wrote some code to work around that. Using the code below you can center you application on your monitor in just 3 lines of code using either VB.NET or C#.
The first thing you’ll notice is that I’m using Screen.PrimaryScreen.WorkingArea and not Screen.PrimaryScreen.Bounds, the bounds of the screen will give me the actual height/width of the monitor as coordinates. But what it doesn’t take into account like the WorkingArea does are any docked items, such as the toolbar. The WorkingArea returns the Bounds, and subtracts off any area unusable by the program to give us the “true” center.
(Source Code) Recenter your window using VB.NET
1 2 3 4 5 6 7 8 9 10 | 'This code was developed by Gerardo Lopez and was downloaded from www.brangle.com 'Complete source code is available at: 'http://www.brangle.com/wordpress/2009/08/how-to-center-a-form-in-vb-net-and-c-sharp/ Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click 'Get the working area of the screen and assign it to a rectangle object Dim rect As Rectangle = Screen.PrimaryScreen.WorkingArea 'Divide the screen in half, and find the center of the form to center it Me.Top = (rect.Height / 2) - (Me.Height / 2) Me.Left = (rect.Width / 2) - (Me.Width / 2) End Sub |
(Source Code) Recenter your window using C#
1 2 3 4 5 6 7 8 9 10 11 | //This code was developed by Gerardo Lopez and was downloaded from www.brangle.com //Complete source code is available at: //http://www.brangle.com/wordpress/2009/08/how-to-center-a-form-in-vb-net-and-c-sharp/ private void button1_Click(object sender, EventArgs e) { //Get the working area of the screen and assign it to a rectangle object Rectangle rect = Screen.PrimaryScreen.WorkingArea; //Divide the screen in half, and find the center of the form to center it this.Top = (rect.Height / 2) - (this.Height / 2); this.Left = (rect.Width / 2) - (this.Width / 2); } |