WPF桌面程序开发怎么实现鼠标窗体穿透点击桌面
WPFwinapi窗体穿透窗体鼠标
博客随笔
909
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);
};
}
以上代码就实现了鼠标穿透窗体点击桌面的其他东西了