开发者

WPF Events in Winforms

I have an Winforms application that is using a WPF control (Avalon Edit if it matters) inside an ElementHost.

It seems to be working fine, but I would like to be able to handle KeyPress events of this control in the Winforms manner (without RoutedCommands and InputGestures), so I though I could just handle the Form's KeyDown event with KeyPreview set, but WPF events don't seem to bubble up to the Form.

So 开发者_如何学编程basically, how can you access a KeyDown event on a WPF control in the Winforms manner?


You can try to add custom event handler for WpfControl itself, instead of trying to connect to WinForm's KeyDown.

Here's example. Let's say: your WinForm is of type Form1, WpfControl is UserControl1, and element host for WpfControl is called (won't ever guess)) - elementHost.

public Form1()
{
    InitializeComponent();
    elementHost.ChildChanged += ElementHost_ChildChanged;
}

private void ElementHost_ChildChanged(object sender, ChildChangedEventArgs e)
{
    var ctr = (elementHost.Child as UserControl1);
    if (ctr == null)
        return;
    ctr.KeyDown += ctr_KeyDown;
}

void ctr_KeyDown(object sender, System.Windows.Input.KeyEventArgs e)
{
    /* your custom handling for key-presses */
}

UPD: e.KeyboardDevice.Modifiers (e is System.Windows.Input.KeyEventArgs) stores info about Ctrl, Alt, etc.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜