获取相对于活动窗口的鼠标单击位置

时间:2012-08-25 14:24:34

标签: c# winapi multiple-monitors mouse-hook

在计算出如何使用低级钩子获取鼠标单击位置沿监视器边界的任何位置时,我会收到一个X Y坐标,该坐标在我的电脑情况下通常包含x: -1680 to +1920y: 0 to 1200之间的值。够容易!

现在的问题是我现在想要计算相对于给定窗口的鼠标位置,所以我使用GetForegroundWindow()GetWindowRect(HandleRef hWnd, out RECT lpRect)来获取我的活动窗口坐标。

我遇到困难的是我需要当前活动桌面(通过激活我是指发生点击的监视器)来计算鼠标点击相对于窗口的坐标。

不幸的是,我无法找到像GetActiveMonitor()或类似的API调用,所以希望有人可以指出我正确的方向?

2 个答案:

答案 0 :(得分:1)

我的猜测是你可以使用if:

知道鼠标的位置
if(mousePosition.X > -1680 && mousePosition.X < 0)
      //We are in monitor 1;
else
      //Monitor 2;

答案 1 :(得分:1)

[DllImport("user32.dll", SetLastError = true)]
 [return: MarshalAs(UnmanagedType.Bool)]
 static extern bool GetWindowRect(IntPtr hWnd, ref RECT lpRect);
 [StructLayout(LayoutKind.Sequential)]
 private struct RECT
 {
     public int Left;
     public int Top;
     public int Right;
     public int Bottom;
  }
Call it as:

  RECT rct = new RECT();
  GetWindowRect(hWnd, ref rct);

获得这样的鼠标位置后

int mouserelativepositionX = mousePosition.X - rct.Left;
int mouserelativepositionY = mousePosition.Y - rct.Top;
相关问题