c# 如何获取其他软件的控件,相对与该软件窗口的相对位置
时间: 2024-06-14 12:07:03 浏览: 5
在C#中,可以使用以下方法获取其他软件的控件相对于当前窗口的相对位置:
```csharp
[DllImport("user32.dll")]
public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
[DllImport("user32.dll")]
public static extern IntPtr FindWindowEx(IntPtr hwndParent, IntPtr hwndChildAfter, string lpszClass, string lpszWindow);
[DllImport("user32.dll")]
public static extern bool GetWindowRect(IntPtr hwnd, out RECT lpRect);
[DllImport("user32.dll")]
public static extern bool ClientToScreen(IntPtr hwnd, ref POINT lpPoint);
public struct RECT
{
public int Left;
public int Top;
public int Right;
public int Bottom;
}
public struct POINT
{
public int X;
public int Y;
}
public void GetControlRelativePosition(string windowTitle, string controlClassName)
{
IntPtr mainWindowHandle = FindWindow(null, windowTitle);
if (mainWindowHandle != IntPtr.Zero)
{
IntPtr controlHandle = FindWindowEx(mainWindowHandle, IntPtr.Zero, controlClassName, null);
if (controlHandle != IntPtr.Zero)
{
RECT controlRect;
GetWindowRect(controlHandle, out controlRect);
POINT relativePosition;
relativePosition.X = controlRect.Left;
relativePosition.Y = controlRect.Top;
ClientToScreen(mainWindowHandle, ref relativePosition);
int relativeX = relativePosition.X - this.Left;
int relativeY = relativePosition.Y - this.Top;
Console.WriteLine("Control relative position: X = {0}, Y = {1}", relativeX, relativeY);
}
else
{
Console.WriteLine("Control not found.");
}
}
else
{
Console.WriteLine("Window not found.");
}
}
```
使用示例:
```csharp
GetControlRelativePosition("OtherWindow", "OtherControl");
```
请注意,上述代码中的"OtherWindow"和"OtherControl"需要替换为实际的窗口标题和控件类名。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)