zoukankan      html  css  js  c++  java
  • WPF调用Win Form

    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

  • 相关阅读:
    Jenkins安装以及邮件配置
    TUXEDO管理命令总结
    QTP的退出函数
    QTP 启动应用软件方法
    Robot framework 和RIDE 关系
    使用pycharm编写和运行RF脚本
    刷题-力扣-102. 二叉树的层序遍历
    刷题-力扣-反转链表
    刷题-牛客-判断链表中是否有环
    刷题-力扣-278. 第一个错误的版本
  • 原文地址:https://www.cnblogs.com/allanli/p/4482165.html
Copyright © 2011-2022 走看看