Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set mouse position not working c#

I've been trying to write a small utility that will modify the boundaries of where my mouse can go on the whole screen. I've used the the global mouse hook library that I found here (I'm using version 1), and then pass the mouse position information from the event it generates to my own function (just a test to see it working for now).

internal void ProcessMouseEvent(System.Drawing.Point point)
{
    Cursor.Position = new Point(50,50);
}

When running it, the mouse does appear to flash to the specified point, but will instantly revert back to where it was before the change if it was a movement event. Only when it was done through a click event does it actually remain at the new position.

like image 796
littlerat Avatar asked Dec 28 '12 01:12

littlerat


People also ask

How do I change the mouse position in C++?

It's basically: Move mouse->Update Variable With Coordinates->Reset Mouse Position. That way you'll never reach the edge of the screen on can keep moving the mouse in any one direction if you wanted to. Well that's what I'm trying to do to implement a camera for DirectX.

How to set mouse pointer position in JavaScript?

To do this, we use document. elementFromPoint(x+px, y+py) in which we pass the position of image cursor. This will gives us the object of the element, the image cursor is on.


2 Answers

To limit where the mouse can go efficiently, you need to use cursor.clip. You can find its documentation here. It will do what you want much easier and is the recommended way.

like image 163
FrostyFire Avatar answered Oct 03 '22 23:10

FrostyFire


The problem here is that the hook gives you a notification of the mouse message. But doesn't prevent it from being processed by the application that is going to actually process the notification. So it gets handled as normal and the mouse moves where it wants to go. What you need to do is actually block the message from being passed on, that requires returning a non-zero value from the hook callback.

The library does not permit you to tinker with the hook callback return value, it is going to require surgery. Beware it is buggy. I'll instead use this sample code. With this sample callback method:

private static IntPtr HookCallback(int nCode, IntPtr wParam, IntPtr lParam) {
    if (nCode >= 0 && MouseMessages.WM_MOUSEMOVE == (MouseMessages)wParam) {
        System.Windows.Forms.Cursor.Position = new Point(50, 50);
        return (IntPtr)1;   // Stop further processing!
    }
    return CallNextHookEx(_hookID, nCode, wParam, lParam);
}

And you'll see it is now solidly stuck. Use Alt+Tab, Alt+D, E to regain control.

like image 40
2 revs Avatar answered Oct 03 '22 22:10

2 revs