Adding this event handler to your form:
private void control_Enter(object sender, EventArgs e)
{
if (sender is Control)
{
var control = (Control)sender;
Cursor.Position = control.PointToScreen(new Point()
{
X = control.Width / 2,
Y = control.Height / 2
});
}
}
you can then subscribe the multiple controls to it that you require to have the cursor "move" to the center of those controls, for example:
button1.Enter += control_Enter;
or alternatively you can assign with the property grid in the designer.
This approach has one caveat, that is if the user clicks on the control with the mouse, the cursor is also centered. This may or may not be desirable behavior for you, depending on your application.
Update based on new requirements for question:
Since you may not have access to modify the source code of the form in question, you can pass a reference to the form you are displaying to a function:
void SubscribeControlsOnEnter(Form form)
{
foreach (Control control in form.Controls)
{
control.Enter += control_Enter;
}
}
or similar, which can iterate through contained controls on your form. If your form has controls nested in containers, you will need to use recursion but should still be possible using this pattern.
For a nested approach, your function to subscribe to controls might look something like this (remember, Form
derives from Control
):
void SubscribeNestedControlsOnEnter(Control container)
{
foreach (Control control in container.Controls)
{
if (control.Controls.Count > 0)
{
SubscribeNestedControlsOnEnter(control);
}
else control.Enter += control_Enter;
}
}
such that when displaying your form, you might invoke in the following manner:
Form1 form = new Form1();
SubscribeNestedControlsOnEnter(form);
form.Show();