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

后端 未结 2 1810
陌清茗
陌清茗 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:52

    Check this code:

    [DllImport("user32.dll")]
    static extern IntPtr GetForegroundWindow();
    
    
    [DllImport("user32.dll")]
    static extern int GetWindowText(IntPtr hWnd, StringBuilder text, int count);
    
    private string GetActiveWindowTitle()
    {
        const int nChars = 256;
        StringBuilder Buff = new StringBuilder(nChars);
        IntPtr handle = GetForegroundWindow();
    
        if (GetWindowText(handle, Buff, nChars) > 0)
        {
         return Buff.ToString();
        }
      return null;
    }
    
    0 讨论(0)
  • 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) ; 
    } 
    
    0 讨论(0)
提交回复
热议问题