2011-05-04 80 views
4

我只是在這裏檢查一些帖子,但沒有一個對我有幫助。在C中獲取活動窗口座標和高度寬度#

我想要做的事情是運行屏幕捕獲的後臺進程。現在我想要一段代碼,它會給我打開X,Y或任何活動/當前窗口(記事本)及其高度和寬度。

就是這樣,沒有別的。

+1

什麼平臺? Silverlight的? WPF?的WinForms? asp.net?安慰? (等) – 2011-05-04 05:31:03

+0

@ Muad'Dib - C#.Net 2.0 – 2011-05-04 07:19:20

+0

這是您正在使用的.net版本。不是你的平臺。 :) – 2011-05-04 16:10:00

回答

12
[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 
} 
+0

非常感謝。我現在只是要測試:) – 2011-05-04 05:57:37

+0

'私人句柄GetActiveWindow()'這是給錯誤處理:/ – 2011-05-04 06:22:45

+0

我已更正了代碼 – Eminem 2011-05-04 13:41:42

1
[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); 
    } 
+0

嗨,歡迎來到stackoverflow。請更多地描述答案。明確的答案將有助於人們理解你的意思,並將增加選擇答案的機會 。 – 2016-09-26 20:59:54