Veriditas
Veriditas

Reputation: 113

Get the focused window name

I'm trying to get the name of the current focused window. Thanks to my research, I have this code :

[DllImport("user32.dll")]
public static extern IntPtr GetForegroundWindow();

[DllImport("user32.dll")]
public static extern int GetWindowText(IntPtr hWnd, StringBuilder lpString, int nMaxCount);

private static bool IsFocused(string name)
{
   StringBuilder buffer = new StringBuilder(256);

   if (GetWindowText(GetForegroundWindow(), buffer, buffer.Length + 1) > 0)
   {
      if (buffer.ToString() == name)
      {
         return true;
      }
   }
   return false;
}

I've checked, the handle returned by GetForegoundWindow() is the correct one. But GetWindowText() always returns a null or negative value.

Upvotes: 2

Views: 1000

Answers (1)

Xiaoy312
Xiaoy312

Reputation: 14477

You need to get the length of the text

[DllImport("user32.dll")]
public static extern IntPtr GetForegroundWindow();

[DllImport("user32.dll")]
public static extern int GetWindowText(IntPtr hWnd, StringBuilder lpString, int nMaxCount);

[DllImport("user32.dll", SetLastError=true, CharSet=CharSet.Auto)]
public static extern int GetWindowTextLength(IntPtr hWnd);

private static bool IsFocused(string name)
{
    var handle = GetForegroundWindow();
    var length = GetWindowTextLength(handle);
    var builder = new StringBuilder(length + 1);

    GetWindowText(handle, builder, builder.Capacity);

    return builder.ToString() == name;
}

Upvotes: 3

Related Questions