Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 753
Migwell Avatar asked Dec 03 '10 23:12

Migwell


1 Answers

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.

like image 59
The Smallest Avatar answered Sep 22 '22 09:09

The Smallest