Making WPF Popups Work in Windowless Applications
I’ve first encountered this issue with my WPF NotifyIcon, and now again while writing a plug-in for Windows Live Writer: If you try to display a WPF popup without any Windows open (the Popup is the only UI component there is), certain controls such as TextBox, ListView, or ListBox don’t receive proper mouse and/or keyboard input, and cannot be selected.
The reason for this issue is buried in the WPF framework, and how it interacts with Windows. Fellow WPF Disciple Andrew Smith pointed me in the right direction:
…because a Popup’s HWND has the WS_EX_NOACTIVATE so the WPF framework will not attempt to actually focus the associated hwnd (because its usually used with a window and you don’t want to deactivate the window when you focus something in the popup).
Accordingly, you’ll have to fiddle with Windows Interop to make things work. Here’s the snippet:
public static class WinApi { /// <summary> /// Gives focus to a given window. /// </summary> [DllImport("USER32.DLL")] public static extern bool SetForegroundWindow(IntPtr hWnd); public static void ActivatePopup(Popup popup) { //try to get a handle on the popup itself (via its child) HwndSource source = (HwndSource)PresentationSource.FromVisual(popup.Child); IntPtr handle = source.Handle; //activate the popup SetForegroundWindow(handle); } }




