lock mouse cursor movement only in a control
I have a picture box which I draw some stuff on it using a bitmap (loading the bitmap as picturebox image after each change of drawing). Now I have a "Add a note" button. this button is somewhere in the mainForm. I want it so when user clicks on this button, the mouse pointer to jump into picturebox control and does not move out of it unless the user has clicked inside the control or pressed Escape key. Is this possible?
I am using this code at the moment:
private void buttonAddNote_Click(object sender, EventArgs e)
{
Cursor = Cursors.Cross;
}
Or a better approach could be on this time when user clicked add a note button, mouse clicks only work within picturebox component (IE user can not click somewhere else in program)
Solution 1:
Modality like that in a user interface is a pretty bad idea. But Winforms does make it possible. You can use the Cursor.Clip property to restrict motion. It can't prevent the user from still accessing, say, the Start menu with a keyboard shortcut, you need to use Capture property to detect that you lost.
public partial class Form1 : Form {
public Form1() {
InitializeComponent();
pictureBox1.MouseCaptureChanged += new EventHandler(pictureBox1_MouseCaptureChanged);
pictureBox1.MouseDown += new MouseEventHandler(pictureBox1_MouseDown);
button1.Click += new EventHandler(button1_Click);
}
private void button1_Click(object sender, EventArgs e) {
var rc = pictureBox1.RectangleToScreen(new Rectangle(Point.Empty, pictureBox1.ClientSize));
Cursor.Position = new Point(rc.Left + rc.Width / 2, rc.Top + rc.Height / 2);
Cursor.Clip = rc;
pictureBox1.Capture = true;
pictureBox1.Cursor = Cursors.Cross;
}
void pictureBox1_MouseDown(object sender, MouseEventArgs e) {
pictureBox1.Capture = false;
}
void pictureBox1_MouseCaptureChanged(object sender, EventArgs e) {
if (!pictureBox1.Capture) {
pictureBox1.Cursor = Cursors.Default;
Cursor.Clip = new Rectangle(0, 0, 0, 0);
}
}
protected override bool ProcessCmdKey(ref Message msg, Keys keyData) {
if (keyData == Keys.Escape) pictureBox1.Capture = false;
return base.ProcessCmdKey(ref msg, keyData);
}
}