Set mouse position not working c#

我怕爱的太早我们不能终老 提交于 2019-12-05 09:57:59

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.

Hans Passant

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.

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