[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool GetWindowRect(HandleRef hWnd, out RECT lpRect);
[StructLayout(LayoutKind.Sequential)]
public struct RECT
{
public int Left; // x position of upper-left corner
public int Top; // y position of upper-left corner
public int Right; // x position of lower-right corner
public int Bottom; // y position of lower-right corner
}
foreach (Process pr in Process.GetProcesses())
{
RECT rc;
GetWindowRect(???, out rc);
我应该为“???”填什么? .它告诉我必须放置一个 HandleRef 对象,但我不知道如何从 Process 方法获取 HandleRef 对象。
最佳答案
如果您需要进程中已有窗口的窗口坐标,还有其他方法可以获得不需要枚举进程的窗口句柄。
对于 WinForms 窗口,使用 Handle
属性。
System.Windows.Forms.Control ... Handle Property @ MSDN
对于 WPF 应用程序,使用 WindowInteropHelper
System.Windows.Interop ... WindowInteropHelper Class @ MSDN
如果您尝试枚举无法直接从 .NET 访问的窗口;例如,从创建超出代码范围的顶级窗口的第 3 方控件,您可能希望通过 win32 EnumWindows
函数进行枚举。
EnumWindows 的 P/Invoke 签名可在此处获得:
User32.dll EnumWindows @ pinvoke.net
添加:
您似乎想枚举所有窗口和相关进程。使用 EnumWindows
,然后调用 GetWindowThreadProcessId
以获取每个窗口的关联进程和非托管线程 ID。
GetWindowThreadProcessId (Win32) @ MSDN
P/Invoke 签名可在此处获得:
User32.dll GetWindowThreadProcessId @ pinvoke.net
最后,您可以通过静态方法 GetProcessById
获取 Process 对象。
添加(#2):
这是一个简短的控制台程序,可以枚举窗口、进程和线程 ID。与您的代码段有一些不同。
- 我使用 IntPtr,而不是 HandleRef。正如其他人所指出的,这可能会让您感到困惑。
- 我没有指定
return
属性。如果需要,您应该可以将其重新添加。 - 我以管理员身份运行;如果您以用户级权限运行,有些事情可能会以不同的方式运行。
关于C# - user32.dll - GetWindowRect 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5098994/