Active window-title

132 views Asked by At

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());
    }
}
1

There are 1 answers

0
Siavash Mortazavi On

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:

using System.Runtime.InteropServices;
using System.Text;

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)
    {        
        // You may want to add a circuit breaker here, e.g. when a key is storked
        while (true)
        {
            Console.WriteLine(GetActiveWindowTitle());
            Thread.Sleep(300);
        }        
    }

    public static string GetActiveWindowTitle()
    {
        const int nChars = 256;
        StringBuilder buffer = new StringBuilder(nChars);
        IntPtr handle = GetForegroundWindow();        

        return GetWindowText(handle, buffer, nChars) > 0 ? buffer.ToString() : string. Empty;
    }
}

p.s. This is a very interesting related project: https://github.com/dotnet/pinvoke