Use IVirtualDesktopNotificationService, IVirtualDesktopNotification
GetWindowDesktop Error
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.