强制WinForms Application.Run方法使用WPF表单

时间:2013-10-28 12:06:57

标签: .net wpf multithreading winforms

我有一个现有的WinForms应用程序。 在这个应用程序中,一个表单在单独的线程中调用:

 var newDialogThread = new Thread(new ThreadStart(ShowMyForm));
 newDialogThread .Name = "CustomerViewThread";
 newDialogThread .IsBackground = true;
 newDialogThread .ApartmentState = ApartmentState.STA;
 newDialogThread .CurrentCulture = Config.CustomerCulture;

public void ShowMyForm()
{
  using(var myForm = new MyForm())
  {
     Application.Run(myForm );
   }
}

现在客户希望使用WPF表单而不是WinForms对话框。应用程序将保留Winforms为基础。

如何正确地重构这部分代码,以便调用我的WPF表单而不是Winforms?

 public void ShowMyForm()
    {
      using(var myWpfForm = new MyWpfForm())
      {
          // Analog of Application Run?
         //Application.Run(myForm );
       }
    }

P.S。我认为可以创建纯WPF窗口而无需将其托管到Winforms。这是主要的情况。

3 个答案:

答案 0 :(得分:2)

听起来您需要编辑(WinFormsMyForm控件以向其中添加ElementHost控件,以便它可以托管您的WPF控件:

MyWpfForm myWpfForm = new MyWpfForm();
ElementHost elementHost = new ElementHost();
elementHost.Child = myWpfForm;
this.Controls.Add(elementHost);

通过这种方式,您可以保持ShowMyForm方法不变。

答案 1 :(得分:1)

This article解释了如何做到这一点。但基本上是:

1)创建/添加“WPF Custom Control Library”类型的新项目

2)添加“Window(WPF)”类型的新项目

3)使用WPF窗口做你的事情

4)从WinForms应用程序中,创建并打开WPF窗口:

using System;  
using System.Windows.Forms;  
using System.Windows.Forms.Integration;  

//Place the following code where you want to open the WPF window
var wpfwindow = new WPFWindow.Window1(); 
ElementHost.EnableModelessKeyboardInterop(wpfwindow); 
wpfwindow.Show();

答案 2 :(得分:0)

我在相关主题中找到了答案: How do I create and show WPF windows on separate threads?

  private void NewWindowHandler(object sender, RoutedEventArgs e)
{       
    Thread newWindowThread = new Thread(new ThreadStart(ThreadStartingPoint));
    newWindowThread.SetApartmentState(ApartmentState.STA);
    newWindowThread.IsBackground = true;
    newWindowThread.Start();
}

private void ThreadStartingPoint()
{
    Window1 tempWindow = new Window1();
    tempWindow.Show();       
    System.Windows.Threading.Dispatcher.Run();
}

http://msdn.microsoft.com/en-us/library/ms741870.aspx