如何获取和设置在C#中的另一个应用程序的窗口位置

我怎样才能获得和设置使用C#的另一个应用程序的位置?

例如,我想获得记事本的左上angular坐标(假设它在100,400处浮动),并且这个窗口的位置是0,0。

什么是最简单的方法来实现呢?

我实际上写了一个开源的DLL只是为了这样的事情。 从这里下载

这将允许您查找,枚举,resize,重新定位,或做任何你想要的其他应用程序窗口及其控制。 还增加了读取和写入窗口/控件的值/文本的function,并对其进行点击事件。 它基本上是写屏幕抓取 – 但所有的源代码都包含在内,所以你想要做的所有事情都与Windows有关。

尝试使用FindWindow ( 签名 )来获取目标窗口的HWND。 然后你可以使用SetWindowPos ( 签名 )来移动它。

您将需要使用som P / Invoke interop来实现这一点。 基本的想法是首先find窗口(例如,使用EnumWindows函数 ),然后使用GetWindowRect获取窗口位置。

David的有用答案提供了重要的指针和有用的链接。

要把它们用在一个自包含的例子中,通过P / Invoke( 包含System.Forms )使用Windows API来实现问题中的示例场景:

 using System; using System.Runtime.InteropServices; // For the P/Invoke signatures. public static class PositionWindowDemo { // P/Invoke declarations. [DllImport("user32.dll", SetLastError = true)] static extern IntPtr FindWindow(string lpClassName, string lpWindowName); [DllImport("user32.dll", SetLastError = true)] static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, uint uFlags); const uint SWP_NOSIZE = 0x0001; const uint SWP_NOZORDER = 0x0004; public static void Main() { // Find (the first-in-Z-order) Notepad window. IntPtr hWnd = FindWindow("Notepad", null); // If found, position it. if (hWnd != IntPtr.Zero) { // Move the window to (0,0) without changing its size or position // in the Z order. SetWindowPos(hWnd, IntPtr.Zero, 0, 0, 0, 0, SWP_NOSIZE | SWP_NOZORDER); } } }