Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Centralise a Form on the Current Screen

0.00/5 (No votes)
5 Jul 2016 1  
How to centralise a Form when using multiple screens

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

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here