I have a WinForms based app with traditional MDI implementation within it except that I'm hosting WPF based UserControls via the ElementHost control as the main content for each of my MDI children. This is the solution recommended by Microsoft for achieving MDI with WPF although there are various side effects unfortunately. One of which is that my Ctrl+Tab functionality for tab switching between each MDI child is gone because the tab key seems to be swallowed up by the WPF controls.
Is there a simple solution to this that will let the Ctrl+tab key sequences reach my WinForms MDI parent so that I can get the built-in tab switching functionality?
In the host WinForm add a PreviewKeyDown handler for the hosted WPF control that captures Ctrl-(Shift)-Tab, activates the next or previous MDI child and marks the event as handled:
TheHostedWpfControl.PreviewKeyDown += (s, e) =>
{
if (e.Key == Key.Tab && ModifierKeys.HasFlag(Keys.Control))
{
ActivateNextMdiChild(ModifierKeys.HasFlag(Keys.Shift));
e.Handled = true;
}
};
And here is the next/prev MDI child activation:
[DllImport("user32.dll", CharSet = CharSet.Auto)]
public static extern IntPtr SendMessage(IntPtr hWnd, int msg, IntPtr wParam, int lParam);
private const int WM_MDINEXT = 0x224;
private void ActivateNextMdiChild(bool backward = false)
{
if (MdiParent != null)
{
MdiClient mdiClient = MdiParent.Controls.OfType<MdiClient>().FirstOrDefault();
if (mdiClient != null)
{
SendMessage(mdiClient.Handle, WM_MDINEXT, Handle, backward ? 1 : 0);
}
}
}