Jacob
Jacob

Reputation: 2414

Restrict Mouse Move only on a Specified Area

private void MoveCursor()
{
   // Set the Current cursor, move the cursor's Position,
   // and set its clipping rectangle to the form. 

   this.Cursor = new Cursor(Cursor.Current.Handle);
   Cursor.Position = new Point(Cursor.Position.X - 50, Cursor.Position.Y - 50);
   Cursor.Clip = new Rectangle(this.Location, this.Size);
}

I am using the above code to Restrict the movement but still I am able to move the mouse outside the form?

Can I restrict the mouse movement to a specified area in the form? Please advise...

Upvotes: 4

Views: 2442

Answers (1)

Neil
Neil

Reputation: 11889

Updated answer:

ClipCursor is the API function you require. You will need to supply screen-based coordinates.

BOOL WINAPI ClipCursor(RECT *lpRect);

take a look at this link for the Win32 API code, and this one for pinvoke from C#.

There is pair of Win32 API functions called SetCapture/ReleaseCapture that will restrict the mouse to a certain window bounds.

You will need to use PInvoke to use them, but this will work.

[DllImport("user32.dll")]
static extern IntPtr SetCapture(long hWnd);

SetCapture(Control.Handle);

One thing to bear in mind, is that if used incorrectly, it's possible that the user will not be able to click the [X] to shut down your application because the mouse will not be able to get to the title bar.

Upvotes: 2

Related Questions