How to get default Ctrl+Tab functionality in WinForms MDI app when hosting WPF UserControls

不想你离开。 提交于 2019-12-23 02:47:54

问题


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?


回答1:


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);
        }
    }
}


来源:https://stackoverflow.com/questions/2933885/how-to-get-default-ctrltab-functionality-in-winforms-mdi-app-when-hosting-wpf-u

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!