[C# Helper]
Index Books FAQ Contact About Rod
[Beginning Database Design Solutions, Second Edition]

[Beginning Software Engineering, Second Edition]

[Essential Algorithms, Second Edition]

[The Modern C# Challenge]

[WPF 3d, Three-Dimensional Graphics with WPF and C#]

[The C# Helper Top 100]

[Interview Puzzles Dissected]

[C# 24-Hour Trainer]

[C# 5.0 Programmer's Reference]

[MCSD Certification Toolkit (Exam 70-483): Programming in C#]

Title: Center the cursor over a particular control in C#

[Center the cursor over a particular control in C#]

Some programs move the mouse to center the cursor over a particular control to make some sort of selection easier. For example, it might move the mouse over a dialog's OK button. Personally I find that annoying as a user, but if you decide you need to do it here's how.

This example uses the following CenterMouseOverControl method to center the cursor over a control.

// Center the mouse over a control. private void CenterMouseOverControl(Control ctl) { // See where to put the mouse. Point target = new Point( (ctl.Left + ctl.Right) / 2, (ctl.Top + ctl.Bottom) / 2); // Convert to screen coordinates. Point screen_coords = ctl.Parent.PointToScreen(target); Cursor.Position = screen_coords; }

The method first finds the center of the control. This position is in the coordinate system used by the parent of the control. If the control is contained directly on the form, then these are form coordinates. If the control is inside some other container, such as a Panel or GroupBox, then those coordinates are with respect to the parent's upper left corner.

Note also that the parent might be contained in another container, making figuring out the absolute positioning of the point tricky.

When you position the mouse, you must do so in screen coordinates. That may seem to make things even more confusing but it actually simplifies matters because you can use the control's parent's PointToScreen method to convert the point directly from the parent's coordinate system to the screen's. The code uses that method and then sets the Cursor object's Position property to the resulting point in screen coordinates.

This example uses the following event handlers to make each button move the mouse over the other button. That means you can just click a button repeatedly to move the cursor back and forth (which is kind of fun if you're easily amused).

// Move the mouse over the other control. private void btnOverThere1_Click(object sender, EventArgs e) { CenterMouseOverControl(btnOverThere2); } private void btnOverThere2_Click(object sender, EventArgs e) { CenterMouseOverControl(btnOverThere1); }

Download the example to experiment with it and to see additional details.

© 2009-2023 Rocky Mountain Computer Consulting, Inc. All rights reserved.