【问题标题】:C# Get the mouse position relative to another process Window [closed]C#获取鼠标相对于另一个进程窗口的位置[关闭]
【发布时间】:2020-11-01 15:49:23
【问题描述】:

我有 2 个窗口,可以是不同大小/不同位置。 最终目标是能够在某个位置点击窗口A,并在同一点相对发送点击窗口B

这是一个解释我想要实现的目标的屏幕:

现在我可以找回:

  1. 窗口 A 把手/矩形
  2. 窗口 B 手柄/矩形
  3. 屏幕上的光标位置

我听说过ScreenToClient/ClientToScreen,我知道我需要找到点击窗口A时的相对鼠标位置,并将点击相对发送到窗口B

另外,发送我的按钮点击我使用:

SendMessage(character.MainWindowHandle, 0x201, IntPtr.Zero, CreateParams(?,?);
SendMessage(character.MainWindowHandle, 0x202, IntPtr.Zero, CreateParams(?,?);

我需要找到两个问号

我现在的代码:

var windowAHandle = Win32Api.GetForegroundWindow();
var windowARect = Win32Api.GetWindowRectangle(windowAHandle);
                        
var windowB = PersosEnLigne.First(w => w.Nom == "Character 2");
var windowBRect = Win32Api.GetWindowRectangle(windowB.Process.MainWindowHandle);
var ptTopLeft = new Win32Api.POINT();
var ptBottomRight = new Win32Api.POINT();
ptTopLeft.x = windowARect.Left;
ptTopLeft.y = windowARect.Top;
ptBottomRight.x = windowARect.Right;
ptBottomRight.y = windowARect.Bottom;
Win32Api.ScreenToClient(windowB.MainWindowHandle, ref ptTopLeft);
Win32Api.ScreenToClient(windowB.MainWindowHandle, ref ptBottomRight);

//I'm not even sure if I need to use ScreenToClient or ClientToScreen

【问题讨论】:

  • 这能回答你的问题吗? How to get window's position?
  • 剩下的就是数学
  • 问题在于数学,我找不到我应该计算的内容。 (我从 2 天就开始了,我的大脑已经累了抱歉)
  • @andI'msureI'mmissingsome 该链接对我没有帮助,因为我已经知道如何使窗口正确
  • @user3673720 请将您的尝试添加到问题中 - 您没有显示任何相关代码。你的计算到底有什么问题?请澄清。

标签: c#


【解决方案1】:

一旦你有了 WindowA 矩形,找到当前光标位置相对于 WindowA 矩形左上角的偏移位置:

Point offsetA = new Point(Cursor.Position.X - windowARect.Left, Cursor.Position.Y - windowARect.Top);

现在计算这个偏移量相对于 WindowA 的大小(宽度/高度)的“百分比”:

double xPct = (double)offsetA.X / (double)(windowARect.Right - windowARect.Left + 1);
double yPct = (double)offsetA.Y / (double)(windowARect.Bottom - windowARect.Top + 1));

现在您可以通过找到 WindowB 的宽度/高度,乘以“百分比”,然后将该数字添加到 WindowB 的左上角来找到 WindowB 中的“相同”点:

int xOffsetB = (int)((double)(windowBRect.Right - windowBRect.Left + 1) * xPct);
int yOffsetB = (int)((double)(windowBRect.Bottom - windowBRect.Top + 1) * yPct);
Point offsetB = new Point(windowBRect.Left + xOffsetB, windowBRect.Top + yOffsetB);

现在您可以使用offsetB 中的 X、Y 值来了解在第二个窗口中单击的位置。

【讨论】:

  • 非常感谢你!那正是我想要的!另一件事,当我使用 SendMessage 将点击发送到另一个窗口时。如何将 offsetB 转换回整个屏幕上的位置? (SendMessage 需要绝对坐标)
  • offsetB 中的坐标已经是绝对坐标,因为GetWindowRect 为您提供屏幕坐标:“检索指定窗口的边界矩形的尺寸。尺寸以屏幕坐标给出相对于屏幕的左上角。"
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-01-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-09-05
相关资源
最近更新 更多