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();
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.
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?!
I use Qt 5.7.0 on Windows 10.
My project files:
Pro file http://pastebin.com/r4JE1eph
cpp file: http://pastebin.com/kfgwB1Xk
Please use the Contact Me page, from the top menu and let’s solve it together.
I solved this issue by using Visual Studio instead Qt. But I am very appreciative to You for trying to help me
Glad you figured it out.