Pages

Ads 468x60px

Sunday, January 6, 2013

How to center a form in the screen that currently holds the cursor.


Hi all! Ever needed a way to center a form in the display that currently harbors the mouse pointer? With the below code and my class, which you can download here, this is very easy. All my code does is take a Point and return the index number of the Screen.AllScreens element that contains the point. You could do many things with this class, and the below is just one of many. The below code will center the form on loading, to the screen the mouse pointer is in. In this way if the user has a multi-monitor system and double clicks the program shortcut icon, the program will start in the screen where the icon resides.

private void Form1_Load(object sender, EventArgs e)

        {

          

            Point location = new Point();

            int CurrentScreencall = CurrentScreencall.CurrentScreenOfPointer(MousePosition);

            location.X = (Screen.AllScreens[CurrentScreencall].Bounds.Width - this.Width)/2;

            location.X = (Screen.AllScreens[CurrentScreencall].Bounds.Height - this.Height) / 2;

            location.Offset(Screen.AllScreens[CurrentScreencall].Bounds.Location);





            this.Location = location;

        }


If you guys have any questions leave comments! Hope this helps someone! :)