Skip to content

Instantly share code, notes, and snippets.

@GeeLaw
Created March 31, 2020 00:23
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save GeeLaw/7c2bc923564fe562425d259caf3f40de to your computer and use it in GitHub Desktop.
Save GeeLaw/7c2bc923564fe562425d259caf3f40de to your computer and use it in GitHub Desktop.
Track the focus of Windows using UI Automation.
/*
Copyright (c) 2020 by Gee Law
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
**/
#pragma comment(lib, "ole32")
#pragma comment(lib, "user32")
#define UNICODE
#define _UNICODE
#include<windows.h>
#include<uiautomation.h>
#include<cstdio>
struct CoInitializeGuard
{
HRESULT const hr;
CoInitializeGuard()
: hr(CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED))
{ }
~CoInitializeGuard() { if (SUCCEEDED(hr)) { CoUninitialize(); } }
operator bool() const { return SUCCEEDED(hr); }
};
struct UIAutomationGuard
{
HRESULT hr;
IUIAutomation *pAutomation;
UIAutomationGuard()
{
hr = CoCreateInstance(CLSID_CUIAutomation,
nullptr, CLSCTX_INPROC_SERVER, IID_IUIAutomation,
reinterpret_cast<void **>(&pAutomation));
}
~UIAutomationGuard()
{
if (pAutomation)
{
pAutomation->Release();
}
}
IUIAutomation *operator ->() const { return pAutomation; }
operator bool() const { return SUCCEEDED(hr); }
};
struct MyHandler : IUIAutomationFocusChangedEventHandler
{
LONG refCount;
HWND prevFocus;
char buffer[1024];
MyHandler()
: refCount(1), prevFocus(nullptr)
{ }
ULONG STDMETHODCALLTYPE AddRef()
{
return InterlockedIncrement(&refCount);
}
ULONG STDMETHODCALLTYPE Release()
{
if (InterlockedDecrement(&refCount))
{
delete this;
return 0;
}
return 1;
}
HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void **ppInterface)
{
if (IsEqualGUID(riid, IID_IUnknown))
{
*ppInterface = static_cast<IUnknown *>(this);
}
else if (IsEqualGUID(riid, IID_IUIAutomationFocusChangedEventHandler))
{
*ppInterface =
static_cast<IUIAutomationFocusChangedEventHandler *>(this);
}
else
{
*ppInterface = nullptr;
return E_NOINTERFACE;
}
AddRef();
return S_OK;
}
HRESULT STDMETHODCALLTYPE HandleFocusChangedEvent(
IUIAutomationElement *pSender)
{
HWND focus = GetForegroundWindow();
if (focus != prevFocus)
{
prevFocus = focus;
GetWindowTextA(focus, buffer, sizeof buffer / sizeof buffer[0]);
std::printf("%s\n", buffer);
}
return S_OK;
}
};
struct Program *program;
struct Program
{
int ExitCode;
BOOL const handler;
CoInitializeGuard *init;
UIAutomationGuard *uia;
MyHandler *pHandler;
HRESULT hrAdd;
Program()
: ExitCode(0),
handler(SetConsoleCtrlHandler(CtrlHandler, TRUE)),
hrAdd(E_UNEXPECTED)
{
if (!handler)
{
ExitCode = -1;
return;
}
init = new CoInitializeGuard();
if (!(bool)*init)
{
ExitCode = -2;
return;
}
uia = new UIAutomationGuard();
if (!(bool)*uia)
{
ExitCode = -3;
return;
}
pHandler = new MyHandler();
if (!SUCCEEDED(hrAdd =
(*uia)->AddFocusChangedEventHandler(nullptr, pHandler)))
{
ExitCode = -4;
return;
}
}
~Program()
{
if (SUCCEEDED(hrAdd))
{
(*uia)->RemoveFocusChangedEventHandler(pHandler);
}
if (pHandler)
{
pHandler->Release();
}
if (uia)
{
delete uia;
}
if (init)
{
delete init;
}
if (handler)
{
SetConsoleCtrlHandler(CtrlHandler, FALSE);
}
}
static BOOL WINAPI CtrlHandler(DWORD fdwCtrlType)
{
if (fdwCtrlType == CTRL_C_EVENT
|| fdwCtrlType == CTRL_BREAK_EVENT
|| fdwCtrlType == CTRL_CLOSE_EVENT
|| fdwCtrlType == CTRL_LOGOFF_EVENT
|| fdwCtrlType == CTRL_SHUTDOWN_EVENT)
{
delete program;
ExitProcess(0);
return TRUE;
}
return FALSE;
}
};
int main()
{
program = new Program();
int ret = program->ExitCode;
if (ret)
{
delete program;
return ret;
}
MSG msg;
while (program && GetMessage(&msg, NULL, 0, 0))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment