GetWindowDesktop Error

Bob Mc 6 Reputation points
2020-12-13T02:30:38.463+00:00

I'm writing some code in C# to determine when a user switches virtual desktops in Windows. The only way I can determine to accomplish this is to set a Windows event hook on the EVENT_SYSTEM_FOREGROUND event, then use the IVirtualDesktopManager::GetWindowDesktopId method to see if the desktop ID has been changed. However, when I switch Windows using the Alt-Tab shortcut, the GetWindowDesktopId fails with the error:

Exception thrown: 'System.Runtime.InteropServices.COMException'
An unhandled exception of type 'System.Runtime.InteropServices.COMException' occurred
Element not found. (Exception from HRESULT: 0x8002802B (TYPE_E_ELEMENTNOTFOUND))

It seems that the window handle that is passed when the Alt-Tab is pressed is not found in the list of valid windows for the GetWindowDesktopId method. Is this because the Alt-Tab display isn't a top level window? If so, how do I reliably determine if the window handle points to a top level window?

Here's a sample of the code.

public void SetWindowsFocusHook()
{
    // Set event capture hook
    eventHook = new WinEventDelegate(WinEventProc);
    SetWinEventHook(EVENT_SYSTEM_FOREGROUND, EVENT_SYSTEM_FOREGROUND, IntPtr.Zero, eventHook, 0, 0, WINEVENT_OUTOFCONTEXT);
}

public void WinEventProc(IntPtr hWinEventHook, uint eventType, IntPtr hwnd, int idObject, int idChild, uint dwEventThread, uint dwmsEventTime)
{
    var windowTitle = GetActiveWindowTitle();
    FocusChanged?.Invoke(this, new FocusChangedEventArgs { Hwnd = hwnd, WindowTitle = windowTitle });
}

static void Main()
{
    winInterop = new WindowsInterop();
    winInterop.FocusChanged += FocusChanged;
    winInterop.SetWindowsFocusHook();
}

static void FocusChanged(object source, FocusChangedEventArgs args)
{
    Guid newDesktopId = desktopManager.GetWindowDesktopId(args.Hwnd);    // Error occurs here!
    if (newDesktopId != currentDesktop)
    {
        logger.Debug("New desktop detected!");
    }
}

The methods available for use with the virtual desktop is very sparse, only three methods. Microsoft added a very useful feature but with limited options to customize it (backgrounds, for example).

Any assistance greatly appreciated. Thanks.

Azure Virtual Desktop
Azure Virtual Desktop
A Microsoft desktop and app virtualization service that runs on Azure. Previously known as Windows Virtual Desktop.
1,569 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
11,007 questions
{count} vote

1 answer

Sort by: Most helpful
  1. Castorix31 85,806 Reputation points
    2020-12-13T07:35:39.787+00:00

    Use IVirtualDesktopNotificationService, IVirtualDesktopNotification


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.