this code example (my own) shows how to limit mouse movement to a specific area (of a Button on a Form) and disable tab-key switching. an existing MouseMove handler is uninstalled, or reinstalled as necessary.
the user re-enables mouse movement by pressing the Escape key while the Button has focus.
review the documentation on Cursor to better understand what is going on.
using System;
using System.Data;
using System.Drawing;
using System.Windows.Forms;
namespace MouseControlDemo_2022
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
DataTable dtbl = new DataTable("Customers");
private void Form1_Load(object sender, EventArgs e)
{
}
private bool MouseMoveSuppressed = false;
private void SuppressMouseMove(Point pt)
{
this.MouseMove -= Form1_MouseMove;
Cursor.Position = this.PointToScreen(pt);
Cursor.Clip = RectangleToScreen(SuppressMouseMoveBtn.Bounds);
MouseMoveSuppressed = true;
}
private void Form1_MouseMove(object sender, MouseEventArgs e)
{
}
private void SuppressMouseMoveBtn_Click(object sender, EventArgs e)
{
if (! MouseMoveSuppressed)
{
SuppressMouseMove(new Point(SuppressMouseMoveBtn.Right, SuppressMouseMoveBtn.Bottom));
}
}
private void SuppressMouseMoveBtn_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Escape)
{
if (MouseMoveSuppressed)
{
this.MouseMove += Form1_MouseMove;
Cursor.Clip = Rectangle.Empty;
}
MouseMoveSuppressed = false;
}
else if (e.KeyCode == Keys.Tab)
{
e.Handled = true;
}
}
}
}