views:

202

answers:

3

In order to take advantage of the spell checking ability of WPF textboxes, I have added one to a user control (with the use of elementhost). This user control is used in various window forms. My current problem is trying to handle keyup events from this textbox but the windows form is unable to "get" any event from the control. I can access the properties of the textbox just fine (i.e. text, length, etc.) but keyboard events don't seem to work.

I have found, however, that the following will bring back events from the WPF textbox:

Public Class MyUserControl

    Private _elementHost As New ElementHost
    Private _wpfTextbox As New System.Windows.Controls.Textbox

    Private Sub MyUserControl_Load(...) Handles Me.Load
        Me.Controls.Add(_elementHost)
        _elementHost.Dock = DockStyle.Fill
        _elementHost.Child = _wpfTextbox

        Dim MyEventInfo As EventInfo
        Dim MyMethodInfo As MethodInfo
        MyMethodInfo = Me.GetType().GetMethod("WPFTextbox_KeyUp") 
        MyEventInfo = _wpfTextBox.GetType().GetEvent("PreviewKeyUp")
        Dim dlg As [Delegate] = [Delegate].CreateDelegate(MyEventInfo.EventHandlerType, Me, MyMethodInfo)
        MyEventInfo.AddEventHandler(_wpfTextBox, dlg)
    End Sub

    Public Sub WPFTextbox_KeyUp(ByVal sender As Object, ByVal e As RoutedEventArgs)
        ' something goes here
    End Sub

End Class

The user control is now able to do something after the PreviewKeyUp event is fired in the WPF textbox. Now, I'm not completely sure how to have the window form containing this user control to work with this.

+1  A: 

Im a C# person not VB so please bear with me.. Basically you could assign the event from your Window rather than within your UserControl.. So in the constructor of your Window assign the PreviewKeyUp:

this.myUserContorl.PreviewKeyUp += new System.Windows.Input.KeyEventHandler(WPFTextbox_KeyUp);

then place the event handler in your Window:

    private void WPFTextbox_KeyUp(object sender, System.Windows.Input.KeyEventArgs e)
    {

    }

Incidentally you needn't go through the hassle of capturing the event in your UserControl as you can still access your TextBox within you UserControl directly from your Window (if you make it public), again from your constructor in your Window:

this.myUserContorl.wpfTextbox.PreviewKeyUp += new System.Windows.Input.KeyEventHandler(WPFTextbox_KeyUp);

I imagine it would look like this in VB (at a guess):

AddHandler myUserContorl.wpfTextbox.PreviewKeyUp, AddressOf WPFTextbox_KeyUp
Mrk Mnl
A: 

ElementHost has a static method called EnableModelessKeyboardInterop(). Try calling it?

ElementHost.EnableModelessKeyboardInterop();

Read more here

rudigrobler
A: 

Seems basic, but did you set the KeyPreview to TRUE on your form?

alt text

halfevil