How to Get the Topmost Window Title using Qt/C++ (for Windows)

In this article I am going to describe how to get the title of the window which has the focus, or in other word is currently active. To be able to achieve this in Qt/C++ you need to use the operating system API functions, in this case Win32 API.

As a starting point you need to add ActiveQt module to your Qt project. To do this add the following line to your Qt *.PRO (qmke project) file:

QT += axcontainer

Next, add the following to your include files:

#include "UIAutomation.h"


Then use the following codes in a function to get the window title of the current active window:

IUIAutomation* uiauto;

CoInitialize(NULL);
HRESULT hr =
	CoCreateInstance(__uuidof(CUIAutomation),
		NULL,
		CLSCTX_INPROC_SERVER,
		__uuidof(IUIAutomation),
		(void**)& uiauto);

HWND topWindow = GetForegroundWindow();

if (topWindow == NULL)
	return;

IUIAutomationElement * windElem;
hr = uiauto->ElementFromHandle(topWindow, &windElem);
if (FAILED(hr))
{
	qDebug() << "Can't access the Window in focus!";
	return;
}

BSTR bWinName;
hr = windElem->get_CurrentName(&bWinName);
if (FAILED(hr))
	return;

QString windowName = QString::fromStdWString(
	std::wstring(
		bWinName, SysStringLen(bWinName)
	)
);
SysFreeString(bWinName);

qDebug() << windowName;
if (uiauto != NULL)
	uiauto->Release();

CoUninitialize();


7 Replies to “How to Get the Topmost Window Title using Qt/C++ (for Windows)”

  1. Hello. I got errors with your code:
    ‘IUIAutomation’ was not declared in this scope
    ‘CUIAutomation’ was not declared in this scope

    Can you help me?
    Thanks.

    1. This code is only for Windows (not Linux, not Mac)
      What version of VS are you using?
      Are you sure you add all the dependency related parts mentioned here?!

          1. I solved this issue by using Visual Studio instead Qt. But I am very appreciative to You for trying to help me

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.