Prevent mouse from leaving my form

user2032433 picture user2032433 · Feb 22, 2013 · Viewed 10.1k times · Source

I've attached some MouseMove and MouseClick events to my program and next up is one of these:

  1. Get "global" mouse movement, so that I can read the mouse location even outside the form.
  2. Prevent my mouse from leaving the form in the first place.

My project is a game so it'd be awesome to prevent the mouse leaving my form like most other games do (ofc. you can move it out if you switch focus with alt+tab fe.) and taking a look at answers to other questions asking for global mosue movement, they seem pretty messy for my needs.

Is there an easy way to prevent my mouse from going outside my form's borders? Or actually to prevent it from going OVER the borders in the first place, I want the mouse to stay inside the client area.


Additional info about the game:

The game is a short, 5-30 seconds long survival game (it gets too hard after 30 seconds for you to stay alive) where you have to dodge bullets with your mouse. It's really annoying when you move your mouse out of the form and then the player (System.Windows.Forms.Panel attached to mouse) stops moving and instantly gets hit by a bullet. This is why preventing mouse from leaving the area would be good.

Answer

Abdusalam Ben Haj picture Abdusalam Ben Haj · Feb 22, 2013

Late answer but might come in handy. You could subscribe the form to MouseLeave and MouseMove events and handle them like this :

    private int X = 0;
    private int Y = 0;

    private void Form1_MouseLeave(object sender, EventArgs e)
    {
        Cursor.Position = new Point(X, Y);
    }

    private void Form1_MouseMove(object sender, MouseEventArgs e)
    {
        if (Cursor.Position.X < this.Bounds.X + 50 )
            X = Cursor.Position.X + 20;
        else
            X = Cursor.Position.X - 20;

        if (Cursor.Position.Y < this.Bounds.Y + 50)
            Y = Cursor.Position.Y + 20;
        else
            Y = Cursor.Position.Y - 20;           
    }

The above will make sure the mouse cursor never leaves the bounds of the form. Make sure you unsubscribe the events when the game is finished.

Edit :

Hans Passants's answer makes more sense than my answer. Use Cursor.Clip on MouseEnter :

private void Form1_MouseEnter(object sender, EventArgs e)
    {
        Cursor.Clip = this.Bounds;
    }

You could free the cursor in case of any error/crash (I'm sure you could catch'em) :

Cursor.Clip = Rectangle.Empty;