WPF与Win32的交互(1)

本文介绍如何在WPF应用程序中嵌入Win32按钮,通过创建自定义Win32ButtonHost类实现跨平台组件交互。该方法利用CreateWindowEx函数创建原生Windows控件,并将其作为子窗口添加到WPF界面。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、把Win32的按钮添加到WPF窗口中

1)添加如下的using指令

using System.Windows.Interop;
using System.Runtime.InteropServices;

2)创建Win32ButtonHost类

public class Win32ButtonHost : HwndHost
  {              
      IntPtr hwndHost = IntPtr.Zero;
      IntPtr hwndButton = IntPtr.Zero;
 
      public int ButtonWidth = 0;
      public int ButtonHeight = 0;
 
      private const int WS_CHILD = 0X40000000;
      private const int WS_VISIBLE = 0X10000000;
      private const int WS_BORDER = 0X00800000;
 
      public Win32ButtonHost(int width, int height)
      {
          ButtonWidth = width;
          ButtonHeight = height;
      }
    //CreateWindowEx函数
    [DllImport("user32.dll", EntryPoint = "CreateWindowEx", CharSet = CharSet.Auto)]
    internal static extern IntPtr CreateWindowEx(
        int dwExStyle,
        string lpszClassName,
        string lpszWindowName,
        int style,
        int x, int y,
        int width, int height,
        IntPtr hwndParent,
        IntPtr hMenu,
        IntPtr hInst,
        [MarshalAs(UnmanagedType.AsAny)] object pvParam
        );
 
    protected override HandleRef BuildWindowCore(HandleRef hwndParent)
    {
        hwndHost = CreateWindowEx(0, "static", "", WS_CHILD | WS_VISIBLE, 0, 0, ButtonWidth, ButtonHeight, hwndParent.Handle, IntPtr.Zero, IntPtr.Zero, 0);
        hwndButton = CreateWindowEx(0, "button", "Win32 Button", WS_CHILD | WS_VISIBLE | WS_BORDER, 0, 0, ButtonWidth, ButtonHeight, hwndHost, IntPtr.Zero, IntPtr.Zero, 0);
        return new HandleRef(this, hwndHost);
    }
 
    //DestoryWindow函数
    [DllImport("user32.dll", EntryPoint = "BuildWindowCore", CharSet = CharSet.Auto)]
    internal static extern bool DestoryWindow(IntPtr hwnd);
 
 
    protected override void DestroyWindowCore(HandleRef hwnd)
    {
        DestoryWindow(hwnd.Handle);
    }
}
 
3)WPF页面中使用Win32ButtonHost类
 
<Grid>
       <Border x:Name="myBorder" Margin="20" BorderBrush="LightBlue"  BorderThickness="2"/>
   </Grid>
Win32ButtonHost  win32ButtonHost= new Win32ButtonHost(100, 50);
 myBorder.Child = win32ButtonHost;

 
 
本文转自Work Hard Work Smart博客园博客,原文链接:http://www.cnblogs.com/linlf03/archive/2011/09/08/2171860.html,如需转载请自行联系原作者
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值