WPF是win form的下一代版本,现在越来越多的公司使用WPF。如何兼容已有的使用win form开发的应用程序呢?下面有三种方式来在WPF中调用win form。
使用WPF中的WindowsFormsHost控件来承载win form的控件或者控件库。
WindowsFormsHost是在WindowsFormsIntegration程序集中,位于System.Windows.Forms.Integration命名空间下面。此控件能够承载的是win form的单一控件或者复合控件,但是不能使用top-level的Form,否则会出现错误。
<Window x:Class="WpfTest.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:winform="clr-namespace:System.Windows.Forms;assembly=System.Windows.Forms"
Title="WPF Invoke winform">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<TextBlock Text="this is only a test of wpf invoking win form"/>
<WindowsFormsHost Grid.Row="1" x:Name="wfh">
<winform:Button Text="I am from win form" Click="Button_Click_1"/>
</WindowsFormsHost>
</Grid>
</Window>
使用WPF中的WindowsInteropHelper来定位和调用win form窗体。
WindowsInteropHelper是在PresentationFramework程序集中,位于System.Windows.Interop命名空间下面。它能够拿到WPF的窗体,并且通过IWin32Window来作为win form的载体。主要代码如下:
public class WindowWapper : System.Windows.Forms.IWin32Window
{
private IntPtr _handle;
public IntPtr Handle
{
get
{
return this._handle;
}
}
public WindowWapper(IntPtr handle)
{
this._handle = handle;
}
}
private void FirstWayToInvoke()
{
var form = WinformExample.Program.CreatInstance();
WindowInteropHelper helper = new WindowInteropHelper(this);
form.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
form.Show(new WindowWapper(helper.Handle));
}
使用Process来直接启动已经存在的win form应用程序。
主要是使用Process.Start()方法来启动一个进程,即win form应用程序。
private static void SecondWayToInvoke(string winformExePath)
{
Process.Start(winformExePath);
}
具体例子:http://files.cnblogs.com/files/allanli/WpfTest.zip