I'd like to know how to grab the Window title of the current active window (i.e. the one that has focus) using C#.
Use the Windows API. Call GetForegroundWindow().
GetForegroundWindow() will give you a handle (named hWnd) to the active window.
Documentation: http://msdn.microsoft.com/en-us/library/ms633505(VS.85).aspx
See example on how you can do this with full source code here:
http://www.csharphelp.com/archives2/archive301.html
[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;
IntPtr handle = IntPtr.Zero;
StringBuilder Buff = new StringBuilder(nChars);
handle = GetForegroundWindow();
if (GetWindowText(handle, Buff, nChars) > 0)
{
return Buff.ToString();
}
return null;
}
Edited with @Doug McClean comments for better correctness.
I agree with Jorge's answer BUT those int
s should be IntPtr
s (both for 64-bit-friendliness and so that you can't do math by mistake).
I agree with @Jorge and @Doug but only if it's in another application or not in your own appdomain. If you want the current window within your application use Form.ActiveForm (winforms) or Application.Current.MainWindow (WPF) to get the active window. Someone who has used WPF more than me, please comment / edit as to whether there's a better way to get active rather than main window for and application in WPF.
Loop over Application.Current.Windows[] and find the one with IsActive = true.
this should do it:
Application.Current.Windows.OfType<YourWindowType>().First(P=> P.IsActive == true)