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

Jam*_*mes 23 c# window window-position

如何使用C#获取和设置另一个应用程序的位置?

例如,我想得到记事本的左上角坐标(让我们说它漂浮在100,400处),此窗口的位置为0,0.

实现这一目标的最简单方法是什么?

Dat*_*ink 35

我实际上是为了这种事情而编写了一个开源DLL. 在这里下载

这将允许您查找,枚举,调整大小,重新定位或对其他应用程序窗口及其控件执行任何操作.还添加了一些功能,用于读取和写入窗口/控件的值/文本,并在其上单击事件.它基本上是用屏幕抓取来编写的 - 但所有源代码都包含在内,所以你想要用windows做的一切都包含在那里.

  • 我很抱歉没有关注我的旧stackoverflow帐户.我找到了原始的DLL并将它和反编译的源代码移动到GitHub:https://github.com/DataDink/WindowScrape. (4认同)

mkl*_*nt0 8

大卫的有用答案提供了关键的指针和有用的链接.

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

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);
        }
    }

}
Run Code Online (Sandbox Code Playgroud)

  • 很有帮助的例子! (2认同)

Dav*_*vid 7

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


dri*_*iis 5

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