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;

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.


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 :).


Tags :

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

  1. Ron

    Said on March 30, 2008 :

    Great post, helped me a lot!

  2. Admin

    Said on March 30, 2008 :

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

  3. Ampelio Attanasi

    Said on May 28, 2010 :

    Great man – you saved my day. :-)

  4. midspace

    Said on November 23, 2011 :

    Thank you!
    I’ve spent the last 2 days narrowing our application down to this little issue.
    I’m happy this one line fixed it.

    The thing is, if you use w.ShowDialog(), this bug doesn’t occur.

1 Trackback(s)

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

Post a Comment