The code below spawns a thread that waits for 5 seconds before iterating (recursively) over all the accessibles (widgets) in the foreground application.
If (during the 5 second delay) I switch to a Windows 10 Metro app (like Calc or Edge) then the call to CoUninitialize in the main thread will result in an access violation. Why?
#include <future>
#include <chrono>
#include <windows.h>
#include <oleacc.h>
#pragma comment(lib,"Oleacc.lib")
// Adapted from https://msdn.microsoft.com/en-us/library/windows/desktop/dd317975%28v=vs.85%29.aspx
HRESULT WalkTreeWithAccessibleChildren(IAccessible* pAcc, int depth)
{
HRESULT hr;
long childCount;
long returnCount;
if (!pAcc)
{
return E_INVALIDARG;
}
hr = pAcc->get_accChildCount(&childCount);
if (FAILED(hr))
{
return hr;
};
if (childCount == 0)
{
return S_FALSE;
}
VARIANT* pArray = new VARIANT[childCount];
hr = AccessibleChildren(pAcc, 0L, childCount, pArray, &returnCount);
if (FAILED(hr))
{
return hr;
};
// Iterate through children.
for (int x = 0; x < returnCount; x++)
{
VARIANT vtChild = pArray[x];
// If it's an accessible object, get the IAccessible, and recurse.
if (vtChild.vt == VT_DISPATCH)
{
IDispatch* pDisp = vtChild.pdispVal;
IAccessible* pChild = NULL;
hr = pDisp->QueryInterface(IID_IAccessible, (void**)&pChild);
if (hr == S_OK)
{
WalkTreeWithAccessibleChildren(pChild, depth + 1);
pChild->Release();
}
pDisp->Release();
}
}
delete[] pArray;
return S_OK;
}
int main(int argc, char *argv[])
{
CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED);
auto future = std::async(std::launch::async,
[]
{
// Switch to a Windows 10 Metro app like the Calculator or Edge.
std::this_thread::sleep_for(std::chrono::milliseconds(5000));
auto hwnd = GetForegroundWindow();
if (!hwnd) abort();
CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED);
IAccessible* pAcc = NULL;
HRESULT hr = AccessibleObjectFromWindow(hwnd, OBJID_CLIENT, IID_IAccessible, (void**)&pAcc);
if (hr == S_OK) {
WalkTreeWithAccessibleChildren(pAcc, 0);
pAcc->Release();
}
CoUninitialize();
}
);
future.wait();
CoUninitialize();
}
The error message is:
Unhandled exception at 0x7722B9E7 (combase.dll) in Test.exe: 0xC0000005: Access violation reading location 0x00000008.