如何在 C# 中获取和设置另一个应用程序的窗口位置
如何使用 C# 获取和设置另一个应用程序的位置?
例如,我想获取记事本的左上角坐标(假设它浮动在 100,400 处)以及该窗口在 0,0 处的位置。
实现这一目标的最简单方法是什么?
How can I get and set the position of another application using C#?
For example, I would like to get the top left hand coordinates of Notepad (let’s say it's floating somewhere at 100,400) and the position this window at 0,0.
What's the easiest way to achieve this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
实际上我专门为这类事情编写了一个开源 DLL。
在此处下载
这将允许您对其他应用程序进行查找、枚举、调整大小、重新定位或执行任何您想要的操作窗口及其控件。
还添加了读取和写入窗口/控件的值/文本以及在其上执行单击事件的功能。它基本上是为了进行屏幕抓取而编写的 - 但所有源代码都包含在内,因此您想要对窗口执行的所有操作都包含在那里。
I actually wrote an open source DLL just for this sort of thing.
Download Here
This will allow you to find, enumerate, resize, reposition, or do whatever you want to other application windows and their controls.
There is also added functionality to read and write the values/text of the windows/controls and do click events on them. It was basically written to do screen scraping with - but all the source code is included so everything you want to do with the windows is included there.
大卫的有用答案提供了关键的指导和有用的链接。
为了将它们用于实现问题中示例场景的独立示例,请通过 P/Invoke 使用 Windows API(
System.Windows.Forms
不是涉及):David's helpful answer provides the crucial pointers and helpful links.
To put them to use in a self-contained example that implements the sample scenario in the question, using the Windows API via P/Invoke (
System.Windows.Forms
is not involved):尝试使用 FindWindow (signature) 获取目标窗口的 HWND。然后您可以使用 SetWindowPos (签名)来移动它。
Try using FindWindow (signature) to get the HWND of the target window. Then you can use SetWindowPos (signature) to move it.
您将需要使用一些 P/Invoke 互操作来实现此目的。基本思想是首先找到窗口(例如,使用 EnumWindows 函数),然后使用 GetWindowRect。
You will need to use som P/Invoke interop to achieve this. The basic idea would be to find the window first (for instance, using the EnumWindows function), and then getting the window position with GetWindowRect.