Tuesday, July 25, 2017

Using Windows API to get Active Window Title

This program will print out the window title every time it changes.  It's a good example of using GetForegroundWindow(), GetWindowTextLength(), and GetWindowText().



 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <Windows.h>
#include <iostream>
#include <string>

using namespace std;

void main()
{
 wstring oldTitle = TEXT("not_real_title");
 while (1)
 {
  HWND winHandle = GetForegroundWindow();
  if (winHandle) {
   int titleLen = GetWindowTextLength(winHandle) + 1;
   wstring winTitle(titleLen, '\0');
   int good = GetWindowText(winHandle, &winTitle[0], titleLen);
   
   if (good)
    if (winTitle!=oldTitle)
     wcout << winTitle << endl;
   oldTitle = winTitle;
   Sleep(50);
  }
 }
}

The one thing that held me up was the second argument to GetWindowText().  The second argument is the variable that holds the value of the window title.  Here's the function definition:

int WINAPI GetWindowText(
  _In_  HWND   hWnd,
  _Out_ LPTSTR lpString,
  _In_  int    nMaxCount
);

Since the second parameter is LPTSTR (Long Pointer T-String), I needed to specify the first element in the string ([0]) and use the address-of (&) to match the types up.  

Strings in C++ / Windows API are the worst.