Uploaded August 2023 | Updated November 2026, 1 day ago
Using win32 dll to wait for an external active window such as Notepad in C#. This supports my automation of desktop apps. #csharp
[DllImport("user32.dll")]
static extern IntPtr GetForegroundWindow();
[DllImport("user32.dll")]
static extern int GetWindowText(IntPtr hWnd, StringBuilder text, int count);
public static string GetActiveWindowTitle()
{
const int nChars = 256;
StringBuilder buff = new StringBuilder(nChars);
IntPtr handle = GetForegroundWindow();
if (GetWindowText(handle, buff, nChars) 0) //greater than here
{
return buff.ToString();
}
return "";
}
public static int WaitForActiveWindow(string title, int seconds)
{
DateTime startTime;
string activeTitle = "";
startTime = DateTime.Now;
activeTitle = GetActiveWindowTitle();
while (!activeTitle.ToLower().Contains(title.ToLower()))
{
//Check for timeout
if ((DateTime.Now - startTime).TotalSeconds seconds) //greater than here
return 1;
//Check every 0.2 seconds
Thread.Sleep(200);
activeTitle = GetActiveWindowTitle();
}
return 0;
}
Using win32 dll to wait for an external active window such as Notepad in C#. This supports my automation of desktop apps. #csharp
[DllImport("user32.dll")]
static extern IntPtr GetForegroundWindow();
[DllImport("user32.dll")]
static extern int GetWindowText(IntPtr hWnd, StringBuilder text, int count);
public static string GetActiveWindowTitle()
{
const int nChars = 256;
StringBuilder buff = new StringBuilder(nChars);
IntPtr handle = GetForegroundWindow();
if (GetWindowText(handle, buff, nChars) 0) //greater than here
{
return buff.ToString();
}
return "";
}
public static int WaitForActiveWindow(string title, int seconds)
{
DateTime startTime;
string activeTitle = "";
startTime = DateTime.Now;
activeTitle = GetActiveWindowTitle();
while (!activeTitle.ToLower().Contains(title.ToLower()))
{
//Check for timeout
if ((DateTime.Now - startTime).TotalSeconds seconds) //greater than here
return 1;
//Check every 0.2 seconds
Thread.Sleep(200);
activeTitle = GetActiveWindowTitle();
}
return 0;
}










