I want to get the string of the title of the currently active window in a C# console application.
My below code does just that. However, it only works when I debug the code slowly line by line. When I just hit run, the while seems to enter an infinite loop. Without the while loop, however, no window title is found (and hence not written to the console) in the first place.
What's wrong? And how to fix it?
using System;
using System.Runtime.InteropServices;
class Program
{
[DllImport("user32.dll")]
static extern IntPtr GetForegroundWindow();
[DllImport("user32.dll")]
static extern int GetWindowText(IntPtr hWnd, System.Text.StringBuilder text, int count);
static void Main(string[] args)
{
IntPtr handle = GetForegroundWindow();
const int nChars = 256;
System.Text.StringBuilder Buff = new System.Text.StringBuilder(nChars);
while (GetWindowText(handle, Buff, nChars) <= 0)
{
// Wait until GetWindowText returns a positive value
}
Console.WriteLine(Buff.ToString());
}
}
Why do you have a loop? If you want to continuously check the active window title, you want to move the
IntPtr handle = GetForegroundWindow();to the loop too, and also I guess you need to slow it down a little bit. Anyway, this works fine for me:p.s. This is a very interesting related project: https://github.com/dotnet/pinvoke