在 C# 中获取活动窗口的坐标、高度和宽度

6

我刚刚查看了这里的一些帖子,但没有一个对我有用。

我想要做的事情是运行一个屏幕捕捉的后台进程。现在我需要一段代码,可以给我当前打开的X、Y或任何活动/当前窗口(比如记事本)以及它的高度和宽度。

只需要这些,不需要其他。


1
什么平台?Silverlight?WPF?WinForms?ASP.NET?控制台?(等等) - Muad'Dib
你需要提供你正在使用的 .NET 版本,而不是你的平台。 :) - Muad'Dib
2个回答

16
[DllImport("user32.dll")]  
static extern IntPtr GetForegroundWindow();  


private IntPtr GetActiveWindow()  
{  
    IntPtr handle = IntPtr.Zero;  
    return GetForegroundWindow();  
}

然后使用 GetWindowRect 获取窗口位置。

[DllImport("user32.dll")]  
[return: MarshalAs(UnmanagedType.Bool)]  
static extern bool GetWindowRect(IntPtr 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  
}

非常感谢。我现在就要测试它 :) - Abhinav Dabral
私有的Handle GetActiveWindow(),这里Handle出现了错误 :/ - Abhinav Dabral

3
    [DllImport("user32.dll")]
    private static extern bool SetProcessDPIAware();
    [DllImport("user32.dll")]
    static extern IntPtr GetForegroundWindow();
    [DllImport("user32.dll")]
    [return: MarshalAs(UnmanagedType.Bool)]
    static extern bool GetWindowRect(IntPtr hWnd, out Rectangle lpRect);

    static void Main()
    {
        SetProcessDPIAware();
        Rectangle t2;
        GetWindowRect(GetForegroundWindow(),out t2);
    }

你好,欢迎来到stackoverflow。请更详细地描述答案。清晰的答案将有助于人们理解您的意思,并增加被选为答案的机会。 - Ashkan S

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接