Center the cursor over a particular control in C#

[center the cursor]

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 Example   Follow me on Twitter   RSS feed   Donate




This entry was posted in controls, user interface and tagged , , , , , , , , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *