Set mouse position not working c#

落爺英雄遲暮 提交于 2019-12-07 04:06:27

问题


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.


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/14063542/set-mouse-position-not-working-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!