【问题标题】:How to get and set the window position of another application in C#如何在 C# 中获取和设置另一个应用程序的窗口位置
【发布时间】:2010-11-24 18:24:12
【问题描述】:

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

例如,我想获取记事本的左上角坐标(假设它浮动在 100,400 的某处),并将此窗口定位在 0,0。

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

【问题讨论】:

    标签: c# window window-position


    【解决方案1】:

    我实际上只是为这种事情编写了一个开源 DLL。 Download Here

    这将允许您查找、枚举、调整大小、重新定位或对其他应用程序窗口及其控件执行任何操作。 还增加了读取和写入窗口/控件的值/文本并在它们上执行单击事件的功能。它基本上是为进行屏幕抓取而编写的 - 但包含所有源代码,因此您想要对 windows 执行的所有操作都包含在其中。

    【讨论】:

    • 非常好的图书馆!
    • 我需要更多的支持来支持这项伟大的工作。谢谢
    【解决方案2】:

    David's helpful answer 提供了重要的指针和有用的链接。

    要将它们用于实现问题中示例场景的自包含示例,通过 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);
            }
        }
    
    }
    

    【讨论】:

    • 非常有用的例子!
    【解决方案3】:

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

    【讨论】:

      【解决方案4】:

      您将需要使用 som P/Invoke 互操作来实现此目的。基本思路是先找到窗口(例如,使用EnumWindows function),然后使用GetWindowRect 获取窗口位置。

      【讨论】:

        猜你喜欢
        • 2012-12-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-09-11
        • 1970-01-01
        • 2021-03-13
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多