开发者

Capture Key in a WPF

I have an WPF UserControl in a WinForm:

Capture Key in a WPF

The green part is the WPF UserControl..

The UserControl code bellow:

public partial class UserControl1 : UserControl
{
    public UserControl1()
    {
        InitializeComponent();
    }

    protected override void OnPreviewKeyUp(KeyEventArgs e)
    {
        base.OnPreviewKeyUp(e);
        MessageBox.Show(e.Key.ToString());
    }
}

XAML:

<UserControl>
    <Grid Background="DarkGreen">
        <Label Content="Label" Margin="64,105,0,0" Name="label1" />
    </Grid>
</UserControl>

Every time I open the tabPage2 I need to "listen" to the keyboard commands.

Actual code does not work (any message when pressing keyboard with the tabPage2 open).

Why?

EDIT 1

Updated some WinForms code:开发者_开发问答

    private void tabControl1_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (this.tabControl1.SelectedIndex == 1)
        {
            ElementHost elHost = (this.tabControl1.SelectedTab.Controls[0] as ElementHost);
            bool success = false;
            if (elHost != null)
            {
                success = elHost.Focus();
                Console.WriteLine("Success : {0}", success);
            }                
        }
    }

Result:

Function: WindowsFormsApplication2.Form1.tabPage2_Enter
Function: WindowsFormsApplication2.Form1.tabControl1_SelectedIndexChanged
Success : True

However, the result is the same: any keyUp is captured by the WPF UserControl.


The events are only processed when the ElementHost has the focus. See here for details.

private void tabControl1_SelectedIndexChanged(object sender, EventArgs e)
{
     (this.tabControl1.SelectedTab.Controls[0] as ElementHost).Focus();
}


This happens because the messaging is different between WinForms and WPF.

Here is a solution I came up with for this.

In your WinForms control listen to the key events of the WPF control

_wpfHost.Child = MyWpfControl;
MyWpfControl.Name = "MyWpfControl";

this.MyWpfControl.PreviewKeyDown += WpfControlOnPreviewKeyDown;

In the WpfControlOnPreviewKeyDown do your logic. I had to bubble up the event to another WinForms control that needed the keyboard events.

private void WpfControlOnPreviewKeyDown(object sender, KeyEventArgs args)
{
    if (args.Key != System.Windows.Input.Key.Enter) return;

    // bubble up the event
    var message = new System.Windows.Forms.Message { WParam = (IntPtr)Keys.Enter };
    this.ProcessKeyPreview(ref message);
}

I only needed the enter key.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜