Search code examples
c#cursorcursor-position

Clipping cursor to a panel


Is there any way I can clip the cursor movement to panel area only? I am trying to get coordinates from a panel and after user clicks the mouse for the first time the cursor should move to panel and stay clipped there until the second mouse click. Thanks for answers.


Solution

  • There are few assumptions I'm making here:

    • You are using a windows form
    • By clipping the cursor you mean moving the cursor

    Here is my sample code to move the cursor from one panel to another:

    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
    
        private void panel1_Click(object sender, EventArgs e)
        {
            Cursor.Position = CenterPoint(panel2);
        }
    
        private void panel2_Click(object sender, EventArgs e)
        {
            Cursor.Position = CenterPoint(panel1);
        }
    
        private Point CenterPoint(Control control)
        {
            return new Point(
                Left + control.Left + control.Width / 2, 
                Top + control.Top + control.Height / 2);
        }
    
    }
    

    You can follow a similar logic on MouseMove event to limit movement

        private void panel1_MouseMove(object sender, MouseEventArgs e)
        {
            if (e.X - panel1.Left < 20 && e.Y - panel1.Top < 20)
            {
                Cursor.Position = CenterPoint(panel1);
                Console.WriteLine($"{e.X} {e.Y}");
            }
        }
    

    That will create a "No-Go" zone on the top left of the panel and if the cursor enters that area we send it back to the center