设置鼠标位置不起作用C# [英] Set mouse position not working c#

查看:128
本文介绍了设置鼠标位置不起作用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);
}

运行时,鼠标的确会闪烁到指定点,但如果是移动事件,鼠标会立即恢复到更改之前的位置.只有通过click事件完成操作后,它才真正保留在新位置.

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.

推荐答案

此处的问题是该挂钩为您提供了鼠标消息的通知.但是并不能阻止将由实际处理通知的应用程序对其进行处理.因此,它会像平常一样得到处理,并且鼠标会移动到它想去的地方.您需要做的实际上是阻止消息传递,这需要从hook回调中返回非零值.

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.

该库不允许您修改hook回调的返回值,这将需要进行手术.当心它是越野车.我将改用此示例代码.使用此示例回调方法:

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);
}

您将看到它现在牢固地卡住了.使用Alt + Tab,Alt + D,E重新获得控制权.

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

这篇关于设置鼠标位置不起作用C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆