How to get active window that is not part of my application?

后端 未结 2 1809
陌清茗
陌清茗 2021-01-01 00:12

How can I get the Window Title that the user currently have focus on? I\'m making a program that runs with another Window, and if the user does not have focus on that window

2条回答
  •  南方客
    南方客 (楼主)
    2021-01-01 00:59

    Use GetForegroundWindow to retrieve the handle of the focused window and GetWindowText to get the window title.

    [ DllImport("user32.dll") ]
    static extern int GetForegroundWindow();
    
    [ DllImport("user32.dll") ]
    static extern int GetWindowText(int hWnd, StringBuilder text, int count);   
    
    static void Main() { 
         StringBuilder builder = new StringBuilder(255) ; 
         GetWindowText(GetForegroundWindow(), builder, 255) ; 
    
         Console.WriteLine(builder) ; 
    } 
    

提交回复
热议问题