我想知道如何使用C#获取当前活动窗口(即具有焦点的窗口)的Window标题.
有关如何使用完整源代码执行此操作的示例:
http://www.csharphelp.com/2006/08/get-current-window-handle-and-caption-with-windows-api-in-c/
[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; }
编辑 @Doug McClean评论更好的正确性.
如果你在谈论WPF,那么使用:
Application.Current.Windows.OfType().SingleOrDefault(w => w.IsActive);