C# 可靠的MouseMove(跳跃)

7

我正在使用这个函数来移动光标。

[DllImport("user32.dll")]
static extern bool SetCursorPos(int X, int Y);

当我使用热键触发时,光标将移动到正确的坐标位置,下次移动鼠标时它将从那个位置继续移动。这是预期的工作方式。
然而,在MouseMove事件中,我需要触发SetCursorPos。如果用户将鼠标移动到特定区域,我希望它能跳转到另一个位置并从那里继续。但现在它会跳转到目标位置,然后立即返回(大约90%的时间)。我该如何避免这种行为?
编辑:我决定通过将光标剪切到1x1像素的正方形中来解决问题,仅在1个mousemove事件中进行。Cursor.Clip(MousePosition, new Rectangle(1, 1))。

4
请发布您的MouseMove事件处理程序代码。 - Jason Watkins
我在MouseMove事件中只是调用那个函数,没有别的操作。 - user1340531
@user1340531:无论如何发布吗? - mpen
3
这往往会遇到“如果两个程序同时这样做会怎么样?”的困境。比如你和接收鼠标移动信息的程序,用户总是吃亏的。 - Hans Passant
2个回答

1
我的猜测是,在您想触发事件的区域上方有另一个控件。如果是这样,该控件正在捕获MouseMove事件。
例如,我在左上角的位置0,0添加了一个绿色的200x200面板。如果鼠标移动到面板上,窗体的MouseMove事件将停止捕获鼠标光标位置。在我的form的mouse_move事件中,我设置了窗体的文本以显示鼠标坐标。请注意,当鼠标实际位于0,0时(由于必须单击SnippingTool.exe来获取屏幕截图,因此无法看到我的光标),窗口文本中的坐标仍为200,200。

enter image description here

为了解决这个问题,在面板的MouseMove事件(或您正在使用的任何控件)中使用与您放置在表单的MouseMove事件中相同的代码。这会导致表单文本中的正确坐标。

enter image description here

以下是代码(显然可以重构为单个方法):

public partial class Form1 : Form
{
    [DllImport("user32.dll")]
    static extern bool SetCursorPos(int X, int Y);

    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_MouseMove(object sender, MouseEventArgs e)
    {
        this.Text = string.Format("X: {0}, Y: {1}", e.X, e.Y);

        if (e.X >= 0 && e.X <= 200)
        {
            if (e.Y >= 0 && e.Y <= 200)
            {
                SetCursorPos(500, 500);
            }
        }
    }

    private void panel1_MouseMove(object sender, MouseEventArgs e)
    {
        this.Text = string.Format("X: {0}, Y: {1}", e.X, e.Y);

        if (e.X >= 0 && e.X <= 200)
        {
            if (e.Y >= 0 && e.Y <= 200)
            {
                SetCursorPos(500, 500);
            }
        }
    }
}

我的MouseMove事件实际上是全局的,只要光标移动,无论我悬停在哪里,它都会被触发。 - user1340531
2
正如其他评论者所述,您需要将这段代码添加到您的问题中。 - Inisheer
1
主要是因为没有“全局”MouseMove事件,除非您安装了全局钩子。 - Cody Gray

0
很难在这么少的信息下说出来(也许你的GUI截图会有所帮助)。 你可以尝试:
    private void Button_MouseMove_1(object sender, MouseEventArgs e)
    {
        SetCursorPos(0, 0);
        e.Handled = true;
    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接