Mar
24th | 2008

Using WinForms with WPF, Watch Out!

Filed under C#, WPF | Posted by Amit

Here is an interesting thing that happened to me at work.

For various reasons the application i am working on has a Windows Form in its base, and most of the controls are WPF, part of them are WinForms. The weirdest thing happened to me as i was trying to open a WPF Window from one of my WPF controls, it was impossible to type in text at any of the Textboxes in that Window. After some checking I found out what was the problem was.

Code example:

private void ShowDialogue()
         {
              System.Windows.Controls.TextBox t =
                   new System.Windows.Controls.TextBox();
              t.Width = 140;
              t.Height = 30;
              Window w = new Window();
              w.Width = 200;
              w.Height = 200;
              w.Content = t;
              w.Show();
          } 

This is a simple code snippet that will show a WPF Window, but as i said before:

If somewhere in the Hierarchy there is a WinForm Control you will not be able to type in text in the TextBox!!!. So weird.

The solution is quite simple, you just need to add the following line of code just before the last line and that’s it.

ElementHost.EnableModelessKeyboardInterop(w);

As we all know, we use an ElementHost whenever we need to host a WPF control on a WinForm. Apparently, Windows Forms catches all the keyboard input and keeps it to himself (That greedy bastard…)! If you want Windows Forms to forward the keyboard input it receives onwards to the WPF window, you need to use the line of code showed above.

Conclusion: If you don’t really really really have to use WPF with WinForms, Don’t. And if you do, try really hard to avoid it :).

Amit.

Tags: , , , , , , , ,

3 Responses to “Using WinForms with WPF, Watch Out!”



  1. By Ron on Mar 30, 2008 | Reply

    Great post, helped me a lot!

  2. By Admin on Mar 30, 2008 | Reply

    No problem
    If you need any more help just contact me.

  1. 1 Trackback(s)

  2. Mar 31, 2008: Wöchentliche Rundablage: WPF, Silverlight 2, ASP.NET MVC, .NET 3.5… | Code-Inside Blog

Post a Comment

Search Dev102