Introduction
This is a small snippet of code that allows you to centralize a Form using one line of code. It takes into account the screen co-ordinates and centers it accordingly
Background
I came to write this because when you want to centralize a form on screen, you don't know which screen it is on and using the primary screen co-ordinates causes inconsistencies.
Using the Code
The code is posted as a standard public
method, but works best when used as an extension method (place in a public
module and use the <Extension()>
attribute).
Public Sub Centralise(ByRef aForm As Form)
Dim currentArea = Screen.FromControl(aForm).WorkingArea
aForm.Top = currentArea.Top + CInt((currentArea.Height / 2) - (aForm.Height / 2))
aForm.Left = currentArea.Left + CInt((currentArea.Width / 2) - (aForm.Width / 2))
End Sub
The code finds the working area of the screen that the form occupies the most area on (as it could be straddling two (or more) screens.
History
- 5th July, 2016: Initial version