Mixing MFC and WPF: Modal Dialogs

2019-04-11 19:24发布

问题:

I'm adding C# WPF dialogs to an existing C++ MFC app, using a C++/CLI interface layer. I've got things working, except I'm having a problem with modality. For example:

  1. MFC app shows a WPF dialog using ShowDialog. Works as expected.
  2. That WPF dialog shows a MFC dialog using DoModal. The WPF dialog is hidden behind the base C++ app, and is not disabled unless I manually change IsEnabled. Not ideal, but it works.
  3. Now, that MFC dialog is closed. Now for some reason the base MFC app is enabled, when it should still be disabled due to the WPF dialog not having been closed. That's bad, as it now allows the user to do crazy things while the WPF dialog is still open.

I have a feeling that it would work better if I could set parent dialogs correctly. But so far I havent been able to set an MFC dialog's parent as a WPF dialog, or vice versa. And, I don't even know if that'd fix it.

Any ideas?

回答1:

When opening a CDialog, the trick is to use a WindowsInteropHelper to get the parent WPF dialog's HWND. Then, you can use CWnd::Attach to wrap that HWND in a CWnd class to pass to the CDialog's constructor.

The problem I had was that I already had the CDialog constructed., but not yet displayed. The various versions of SetParent can only be used if your target child window already has a valid handle. I had to write a new function in my CDialog class to set m_wndParent, which is what it uses as the parent when it finally creates the dialog. Then everything works great!

Somehow creating WPF dialogs from MFC dialogs "just works". It's magic.



回答2:

When showing the WPF dialog, are you using the HwndSource class to wrap the WPF window? If so, you may be able to ::SetParent the WPF window as well as use the HwndSource.Handle property to set the sub-child's parent.