// C/C++ #include // Windows SDK #include // Windows Shell #include #include #include #include // ATL/COM #include IShellDispatch* GetShellDispatch_v1() { HRESULT hr; CComPtr spShellDisp; hr = CoCreateInstance(CLSID_Shell, nullptr, CLSCTX_INPROC, IID_IShellDispatch, (void**)&spShellDisp); return SUCCEEDED(hr) && spShellDisp ? spShellDisp.Detach() : nullptr; } IShellDispatch* GetShellDispatch_v2() { IShellDispatch* pShellDispatch = nullptr; CComPtr spShellWindows; if (SUCCEEDED(::CoCreateInstance(CLSID_ShellWindows, nullptr, CLSCTX_LOCAL_SERVER, IID_PPV_ARGS(&spShellWindows)))) { HWND hDesktop; CComPtr spDisp; CComVariant varEmpty; if (SUCCEEDED(spShellWindows->FindWindowSW(&varEmpty, &varEmpty, SWC_DESKTOP, (long*)&hDesktop, SWFO_NEEDDISPATCH, &spDisp))) { if (hDesktop != nullptr && hDesktop != INVALID_HANDLE_VALUE) { CComPtr spShellBrowser; if (SUCCEEDED(IUnknown_QueryService(spDisp, SID_STopLevelBrowser, IID_PPV_ARGS(&spShellBrowser)))) { CComPtr spShellView; if (SUCCEEDED(spShellBrowser->QueryActiveShellView(&spShellView))) { CComPtr spBackgroundDisp; if (SUCCEEDED(spShellView->GetItemObject(SVGIO_BACKGROUND, IID_PPV_ARGS(&spBackgroundDisp)))) { DWORD dwProcessId; if (::GetWindowThreadProcessId(hDesktop, &dwProcessId) && dwProcessId) { ::AllowSetForegroundWindow(dwProcessId); } if (CComQIPtr spShellFolderViewDual = spBackgroundDisp) { CComPtr spDisp; if (SUCCEEDED(spShellFolderViewDual->get_Application(&spDisp))) { if (CComQIPtr spShellDispatch = spDisp) { pShellDispatch = spShellDispatch.Detach(); } } } } } } } } } return pShellDispatch; } int main() { CoInitialize(nullptr); IShellDispatch* pShellDispatch = nullptr; // v1 pShellDispatch = GetShellDispatch_v1(); std::cout << pShellDispatch << std::endl; pShellDispatch && pShellDispatch->Release(); // v2 pShellDispatch = GetShellDispatch_v2(); std::cout << pShellDispatch << std::endl; pShellDispatch && pShellDispatch->Release(); CoUninitialize(); return 0; }