【问题标题】:Mutil monitor mouse tracking多显示器鼠标跟踪
【发布时间】:2011-08-31 07:17:20
【问题描述】:

我需要跟踪鼠标位置。虽然我尝试了几种方法来做到这一点,但如果鼠标在另一台显示器上,我永远无法跟踪/捕捉位置。

    [DllImport("user32.dll")]
    public static extern bool GetCursorPos(ref Point pt);

    [DllImport("user32.dll")]
    public static extern bool GetCursorInfo(out CURSORINFO pci);

    public void GetPosition(out int X, out int Y)
    {
        Point pt = new Point(0, 0);
        X = Y = 0;

        if (MouseMonitor.GetCursorPos(ref pt))
        {
            X = pt.X;
            Y = pt.Y;
        }

这有效,但仅在一个屏幕上有效。我还读到我可能会尝试 GetCursorInfo。我已经尝试过了,但它总是返回错误。 [DllImport("user32.dll")] public static extern bool GetCursorInfo(out CURSORINFO pci);

有什么建议吗?我的目标是跟踪鼠标位置(在我自己的应用程序之外),无论它在哪个屏幕上。

【问题讨论】:

    标签: mouse mouseevent tracking


    【解决方案1】:

    您的示例代码适用于我的双显示器系统...

    您实际上可以通过使用 .NET Framework 简化一些事情:System.Windows.Forms.Cursor 类具有静态 Position 属性。

    例如,我创建了一个新的 Windows 窗体项目,然后将 System.Windows.Forms.Timer 拖到窗体上。我将 Enabled 属性设置为 true,并将此代码添加到 Tick 事件中:

    this.Text = string.Format("{0}, {1}", Cursor.Position.X, Cursor.Position.Y);
    

    运行该项目,它在我的两台显示器上都按预期工作...

    【讨论】:

    • 非常感谢您的建议。
    • 这段代码有什么改进吗?如果没有,您能否提供更多关于光标跟踪如何在另一台显示器上不起作用的具体信息?
    【解决方案2】:

    使用 DWORD GetMessagePos() - 它为您提供最后一个 Windows 消息鼠标位置。但要小心,它返回 DWORD,但里面有两个压缩包(16 位有符号整数)。所以 LOWORD/HIWORD 宏(或相应的 C#)将不起作用。

    http://msdn.microsoft.com/en-us/library/ms644938(VS.85).aspx

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多