WPF:与windows窗体进行交互

源自《WPF编程宝典》总结小记。

混合窗口和窗体

  1. 显示模态窗口和窗体

从WPF应用程序中显示模态窗体很简单,如WPF中:

Form1 frm=new Form1();
if(frm.ShowDialog()==System.Windows.Form.DialogResult.OK)
{
    MessageBox.Show("You clicked OK in a Windows Forms from.");    
}

在windows窗体应用程序显示WPF的方法:

Window1 win=new Window1;
if(Win.ShowDailog()==ture)
{
  MessageBox.Show("You clicked OK in a WPF window.");
}
  1. 显示非模态窗口和窗体

在Windows窗体中非模态显示WPF,需如下:
引入WindowsFormsIntegration.dll程序集

Window1 win=new Window();
ElementHost.EnableModelessKeyboardInterop(win);
win.show();

在WPF应用程序中显示非模态的Windows窗体,需:
只需要在显示任何窗体之前调用(一般启动时)调用

WindowsFormsHost.EnableWindowsFormsInterop();
Form1 frm=new Form1();
frm.Show();

PS:一个问题:在WPF中显示Form窗体时,Form会使用旧的XP的控件风格,如想支持新WPF风格,如下

解决办法:只需在显示所有Windows窗体内容之前调用EnableVisualStyle()方法。
public partial class App:System.Windows.Appliation
{
    protected override void OnStartup(StartupEventArgs e)
    {
        //Raises the Startup event.
        base.OnStartup(e);
        System.Windows.Forms.Application.EnableVisualStyles();
    }
}

创建具有混合内容的窗口

  1. WPF和Windows窗体“空域”--不允许的情况

“空域规则”:指示WPF和Windows窗体必须总是使用它们自己的不同窗口区域,即它们专门管理的区域
具体就是:如果在WPF内容之上放置Windows窗体内容,将发现Windows窗体内容总在上面。
在Windows窗体之上放置WPF内容,根据Z索引显示。ps:Windows窗体的每个控件为单独窗口,WPF为一个根窗口。
clipboard.png

  1. 在WPF中驻留Windows窗体控件

代码如下:

<Window x:Class="InteroperabilityWPF.HostWinFormControl"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:wf="clr-namespace:System.Windows.Forms;assembly=System.Windows.Forms"
    xmlns:sys="clr-namespace:System;assembly=mscorlib"
    Title="HostWinFormControl" Height="300" Width="300"
    >
  <Grid>
    <Grid.RowDefinitions>
      <RowDefinition Height="Auto"></RowDefinition>
      <RowDefinition Height="Auto"></RowDefinition>
    </Grid.RowDefinitions>
    
    
    <WindowsFormsHost Margin="10" Name="host">      
      <wf:MaskedTextBox x:Name="maskedTextBox" Mask="(999)-000-0000" MaskInputRejected="maskedTextBox_MaskInputRejected" ValidatingType="{x:Type sys:Int32}"></wf:MaskedTextBox>
    </WindowsFormsHost>

    <Label Margin="5"  Name="lblErrorText" Grid.Row="1"></Label>
  </Grid>
</Window>
  • 使用WPF和Windows窗体用户控件
  • 在Windows窗体中驻留WPF控件
  • Win32互操作

ps:可以使用System.Windows.Interop.HwndHost类在WPF中驻留Win32.WindowsFormsHost继承于HwndHost
HwndSource是HwndHost的补充,它可将任何WPF可视化对象或元素封装到hwnd中。同时HwndHost.RootVisual属性设置为顶级元素,然后将HwndSource放置到窗口中。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值