I have a canvas in which I have an image. I can move that image using the mouse (drag-n-drop). I want to prevent the user to move the image outside of the canvas.
Is there any way I can trap the mouse pointer so it can only move inside the canvas? So when the user tries to move the mouse outside the canvas, the cursor would remain at the edge of the canvas.
One example of this behavior would be when moving a window, you can’t move it on the taskbar. When you try to move it on the taskbar, the mouse cursor stays on the edge of the taskbar, refusing to move on top of the taskbar.
After more searching, I found there is a function in user32.dll called ClipCursor that does exactly what I want.
Here is an example of a sample app that traps the mouse cursor. When clicking Button1, the cursor will be constrained in a rectangle at (10,10,500,500). When pressing Button2 (or closing the app), the cursor will be free again.
XAML:
CS: