modal WPF dialog hosted in a Win32 app doesn't receive keyboard events

I've got a WPF dialog that I want to display in a Win32 app as a non-modal Window. Calling window.Show() correctly displays the window, and all mouse events are handled properly by it, but all keyboard event are handled by the parent Win32 window, so that even if a user has given focus to a textbox, any typed text shows up in the parent Win32 window!

This seems to be a known problem in WinForms/WPF interop, and is fixed in that case by calling ElementHost.EnableModelessKeyboardInterop before displaying the dialog. This causes a new message filter to be added to the WinForms message loop, so that keyboard events can be intercepted and appropriately routed to the WPF dialog.

Unfortunately my host application is not a WinForms app, so I don't have the option to call EnableModelessKeyboardInterop . Is there any way to do a similar thing in a Win32 app?


You can forward the keyboard messages, but you'll need to do the work yourself.

The basic idea is as follows:

  • Once your WPF window has been created and shown, get its HwndSource :

    HwndSource source = HwndSource.FromVisual(wnd) as HwndSource;

  • In your message loop, whenever you get a keyboard message, cast the HwndSource to IKeyboardInputSink , and call the appropriate method.

  • Basically, if you get a WM_KEYDOWN , you should call TranslateAccelerator() , or if you get a WM_CHAR you should call TranslateChar() . The documentation for IKeyboardInputSink isn't great, but it does specify which methods handle which messages. The method will return true if it has handled message, so you will know if you need to process the message in the Win32 side or not.

    链接地址: http://www.djcxy.com/p/25918.html

    上一篇: Emacs和Vim之间的差异

    下一篇: 在Win32应用程序中托管的模态WPF对话框不会收到键盘事件