Windows窗体与WPF窗体相互调用

一.WPF窗体调用windows窗体

(一)在wpf窗体中,若想调用windows窗体,有两种方法:

1.直接调用        

 private void btnOpenWindows2_Click(object sender, RoutedEventArgs e)
        {
            //直接调用
            Form1 form1=new Form1();
            form1.ShowDialog();
        }
2.借助WindowInteropHelper和WindowWrapper。 WindowInteropHelper 类用于 协助 Windows Presentation Foundation (WPF) 与 Win32 代码之间的互操作。

 private void btnOpenWindows_Click(object sender, RoutedEventArgs e)
        {
            //借助WindowInteropHelper和WindowWrapper
            Form1 form1 = new Form1();
            WindowInteropHelper helper=new WindowInteropHelper(this);
            form1.StartPosition = FormStartPosition.CenterParent;
            form1.ShowDialog(new WindowWrapper(helper.Handle));
        }
其中WindowWrapper是自己定义的类,如下:
public class WindowWrapper : System.Windows.Forms.IWin32Window
    {
        public WindowWrapper(IntPtr handle)
        {
            _hwnd = handle;
        }

        public IntPtr Handle
        {
            get { return _hwnd; }
        }

        private IntPtr _hwnd;
    }
(二)如果在wpf窗体中,以非模态方式调用windows窗体时,需要注意使用 ElementHost类来沿着正确的窗口或窗体转发键盘事件消息

1.在C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\v3.0下找到 WindowsFormsIntegration.dll。将该dll引用进WPF中
2.调用WindowsFormsHost.EnableWindowsFormsInterop( )方法
        private void btnOpenWindows2_Click(object sender, RoutedEventArgs e)
        {
            //直接调用
            WindowsFormsHost.EnableWindowsFormsInterop();//需要在WPF应用程序中显示一个非模态的Windows窗体
            Form1 form1=new Form1();
            form1.Show();
        }
(三)在windows窗体中调用wpf窗体
1.建立wpf项目
2.建立windows窗体项目
3.在windows窗体项目中引用wpf项目
4.如果想在windows窗体中访问wpf窗体,还需要引用几个dll:

PresentationCore

PresentationFramework

System.Xaml

WindowsBase

WindowsFormsIntegration

Windows窗体与WPF窗体相互调用_第1张图片

5.如果在windows窗体中,以非模态方式调用wpf窗体时,需要注意使用 ElementHost类来沿着正确的窗口或窗体转发键盘事件消息
 private void btnOpenWPF_Click(object sender, EventArgs e)
        {
            System.Windows.Window wpfwindow = new WpfApplication3.UserDefineWindow();
            //使WPF窗体响应键盘输入
            ElementHost.EnableModelessKeyboardInterop(wpfwindow);
            //设置WPF窗体的owner,使其WindowStartupLocation.CenterOwner生效。
            WindowInteropHelper helper = new WindowInteropHelper(wpfwindow);
            helper.Owner = this.Handle;
            wpfwindow.WindowStartupLocation = WindowStartupLocation.CenterOwner;
            wpfwindow.Show();
        }




你可能感兴趣的:(c#,wpf)