Yuan天空
Yuan天空
  • 我的主页
  • 博客随笔
  • 软件作品
    • TK精灵(进程守护)
    • 远程运维助手
    • DicomStoreSCU
    • TKOCR(离线OCR)
    • 更多...
  • 学习资源
  • 网址收藏
  • HTML模板
一个不专业的.NET开发者博客
  1. 主页
  2. 博客
  3. 发布页

WPF桌面程序开发怎么实现鼠标窗体穿透点击桌面

WPFwinapi窗体穿透窗体鼠标
博客随笔 2018-10-25 919

C#怎么实现WPF 鼠标穿透窗体?

之前做过一个基于wpf的桌面弹幕软件的需求, 要求一个透明全屏窗体悬浮于桌面,但要求这层窗体不能影响鼠标的其他操作,即鼠标可以穿透透过窗体点击桌面的其他东西

不多说上代码:

首先前端窗体变透明需要添加三个属性

AllowsTransparency="True"
Background="Transparent"
WindowStyle="None"

如下

<Window x:Class="WpfApp1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfApp1"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800"

        AllowsTransparency="True"
        Background="Transparent"
        WindowStyle="None"
        >
    <Grid>
        <Label VerticalAlignment="Center" HorizontalAlignment="Center" Content="我是测试窗体" FontSize="100" />
    </Grid>
</Window>

利用win32 接口 实现窗体透明可穿透

///win32 api
private const int WS_EX_TRANSPARENT = 0x20;
private const int GWL_EXSTYLE = (-20);

[DllImport("user32", EntryPoint = "SetWindowLong")]
private static extern uint SetWindowLong(IntPtr hwnd, int nIndex, uint dwNewLong);

[DllImport("user32", EntryPoint = "GetWindowLong")]
private static extern uint GetWindowLong(IntPtr hwnd, int nIndex);

在窗体Main函数中调用

public MainWindow()
{
    InitializeComponent();
    this.SourceInitialized += delegate 
    { 
    IntPtr hwnd = new WindowInteropHelper(this).Handle; 
    uint extendedStyle = GetWindowLong(hwnd, GWL_EXSTYLE); 
    SetWindowLong(hwnd, GWL_EXSTYLE, extendedStyle |
	WS_EX_TRANSPARENT); 
   };
}

以上代码就实现了鼠标穿透窗体点击桌面的其他东西了

相关文章推荐
01. WPF 使用MahApps.Metro
02. WPF DataGrid不同数据源如何动态生成不同字段名的表格
03. wpf Inkcanvas怎么保存为透明的图片
04. WPF开发样式文件的四种引用方式
05. WPF Rectangle实现 虚线边框矩形 超简单
06. XP系统下运行.net framework 4.0程序出现如下异常
07. WPF+MVVM简单实际应用实例:打造一个任务管理器
08. Windows桌面开发优秀的WPF界面开源UI组件 MahApps.Metro
09. WPF实现窗体接收鼠标拖拽的文件例子
问题反馈/学习建议
1. 文明上网,理性表达,营造舒适的学习氛围
2. 请不要反馈提交与本页主题无关内容
相关服务/资源推荐
C#控件/wpf实例/WPF源码/xaml源文件/Demo程序
Loading...
C# .NET WPF UI界面控件库源码|控件源码|
Loading...
相关资源推荐
01. wpf实现大屏幕弹幕播放效果特效源码新手可参考下.rar
02. [人脸检测]基于C#OpenCvSharp+haarcascade人脸、人眼模型实现人脸检测源码
03. C#使用WinAPI获取指定窗体及按钮控件句柄实现自动模拟点击工具源码
04. WPF实现读取USB摄像头实时视频展示以及导出实时截图的C#源码例子
05. WPF实现的自定义工作大日历排班Calendar控件模板的例子源码
06. C#+WPF实现模仿实现的网易云音乐客户端源码