VS 2015. Native C++ development. UIAutomation client issue.
If your client application get IUIAutomationElement usingElementFromHandle and server application closed before your app released the element, User Object leak occur. Further call of theRelease() seems to have zero effect.
Below you can find a complete source code that reproduces the problem.
Run the code below and then run and close calc.exe several times, you will see the number of opened User Objects raises each time you run new instance of the calc.exe.
Am I doing something wrong or this is a UIAutomation problem?
#include <Windows.h> #include <UIAutomation.h> DWORD WINAPI ScanThreadProc(LPVOID lpParameter) { MSG msg; PeekMessage(&msg, NULL, NULL, NULL, PM_NOREMOVE); CoInitializeEx(NULL, COINIT_MULTITHREADED); IUIAutomation *g_pAutomation = NULL; HRESULT hResult = CoCreateInstance(__uuidof(CUIAutomation), NULL, CLSCTX_INPROC_SERVER, __uuidof(IUIAutomation), (void**)&g_pAutomation); IUIAutomationElement *calc_ui = NULL; HWND CalcUIHWND = NULL; while (true) { while (PeekMessage(&msg, NULL, NULL, NULL, PM_REMOVE)) { TranslateMessage(&msg); DispatchMessage(&msg); }; Sleep(1); CalcUIHWND = FindWindow(L"CalcFrame", NULL); if (CalcUIHWND == NULL) continue; hResult = g_pAutomation->ElementFromHandle(CalcUIHWND, &calc_ui); if (FAILED(hResult)) { if (calc_ui != NULL) { calc_ui->Release(); calc_ui = NULL; } continue; } if (calc_ui != NULL) { Sleep(1000); calc_ui->Release(); calc_ui = NULL; } } return 0; } int CALLBACK WinMain( _In_ HINSTANCE hInstance, _In_ HINSTANCE hPrevInstance, _In_ LPSTR lpCmdLine, _In_ int nCmdShow ) { WaitForSingleObject(CreateThread(NULL, 0, ScanThreadProc, 0, 0, 0), INFINITE); return 0; }