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
