How do I get the title of the current active window using c#?
C#.NetWindowsWinformsC# Problem Overview
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#.
C# Solutions
Solution 1 - C#
See example on how you can do this with full source code here:
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;
}
Edited with @Doug McClean comments for better correctness.
Solution 2 - C#
If you were talking about WPF then use:
Application.Current.Windows.OfType<Window>().SingleOrDefault(w => w.IsActive);
Solution 3 - C#
Based on GetForegroundWindow function | Microsoft Docs:
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
static extern IntPtr GetForegroundWindow();
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
static extern int GetWindowText(IntPtr hWnd, StringBuilder text, int count);
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
static extern int GetWindowTextLength(IntPtr hWnd);
private string GetCaptionOfActiveWindow()
{
var strTitle = string.Empty;
var handle = GetForegroundWindow();
// Obtain the length of the text
var intLength = GetWindowTextLength(handle) + 1;
var stringBuilder = new StringBuilder(intLength);
if (GetWindowText(handle, stringBuilder, intLength) > 0)
{
strTitle = stringBuilder.ToString();
}
return strTitle;
}
It supports UTF8 characters.
Solution 4 - C#
Loop over Application.Current.Windows[]
and find the one with IsActive == true
.
Solution 5 - C#
Use the Windows API. Call GetForegroundWindow()
.
GetForegroundWindow()
will give you a handle (named hWnd
) to the active window.
Documentation: GetForegroundWindow function | Microsoft Docs
Solution 6 - C#
If it happens that you need the Current Active Form from your MDI application: (MDI- Multi Document Interface).
Form activForm;
activForm = Form.ActiveForm.ActiveMdiChild;
Solution 7 - C#
you can use process class it's very easy. use this namespace
using System.Diagnostics;
if you want to make a button to get active window.
private void button1_Click(object sender, EventArgs e)
{
Process currentp = Process.GetCurrentProcess();
TextBox1.Text = currentp.MainWindowTitle; //this textbox will be filled with active window.
}