c++winapiwindows-10-desktopvirtual-desktop

How to use the IVirtualDesktopManager interface in C++/Win32


I need to search for maximized windows from Win32 (by using EnumWindows) but I also want to filter for windows which are on the current virtual desktop. On MSDN, I found a page about the IVirtualDesktopManager interface but there seems to be no information on how to use this interface.

IVirtualDesktopManager::IsWindowOnCurrentVirtualDesktop(/*args...*/);

Throws the following error:

Non static member reference must be relative to a specific object

VirtualDesktopManager mVirtualDeskManager;
mVirtualDesktopManager.IsWindowOnCurrentVirtualDesktop(/args...*/)

Throws this error:

Incomplete type is not allowed

I have only found solutions on using the IVirtualDesktopManager interface in C# yet.


Solution

  • IVirtualDesktopManager is a COM interface. You need to instantiate the COM object that implements the interface.

    Based on code from this blog, you can use IServiceProvider to access IVirtualDesktopManager (and IVirtualDesktopManagerInternal, which has much more functionality than IVirtualDesktopManager has), eg:

    IServiceProvider* pServiceProvider = NULL;
    HRESULT hr = ::CoCreateInstance(
        CLSID_ImmersiveShell, NULL, CLSCTX_LOCAL_SERVER,
        __uuidof(IServiceProvider), (PVOID*)&pServiceProvider);
    
    if (SUCCEEDED(hr))
    {
        IVirtualDesktopManager *pDesktopManager = NULL;
        hr = pServiceProvider->QueryService(__uuidof(IVirtualDesktopManager), &pDesktopManager);
    
        if (SUCCEEDED(hr))
        {
            BOOL bIsOnCurrentDesktop = FALSE;
            hr = pDesktopManager->IsWindowOnCurrentVirtualDesktop(hWnd, &bIsOnCurrentDesktop);
    
            if (SUCCEEDED(hr))
            {
                // use bIsOnCurrentDesktop as needed...
            }
    
            pDesktopManager->Release();
        }
    
        pServiceProvider->Release();
    }