Click here to Skip to main content
15,891,033 members
Articles / Desktop Programming / Windows Forms
Tip/Trick

Centralise a Form on the Current Screen

Rate me:
Please Sign up or sign in to vote.
2.33/5 (2 votes)
5 Jul 2016CPOL 6.4K   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).

VB.NET
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, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
United Kingdom United Kingdom
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
-- There are no messages in this forum --