首页 > 解决方案 > 如何在不点击的情况下制作透明的 WPF 应用程序?

问题描述

你能告诉我如何在WPF中制作一个透明窗口而不让它点击吗?我已经为此苦苦挣扎了很长时间。

标签: c#wpf

解决方案


除了通常AllowsTransparency="True"WindowStyle="None"自定义窗口布局外,还可以添加Background="#01FFFFFF"到您的 Window。任何未显式绘制的部分都将显示为(几乎)透明(在深色背景下会有非常微弱的阴影),但这些区域将捕获鼠标点击,从而阻止点击进入其他窗口。

以下是如何创建具有中空部分的非矩形窗口的示例

HollowView.xaml

<Window
    x:Class="CustomWindowChromeDemo.HollowView"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    AllowsTransparency="True"
    Background="#01ffffff"
    WindowStyle="None">

    <Grid
        HorizontalAlignment="Stretch"
        VerticalAlignment="Stretch">
        <Path
            Data="F0 M 0,0 L 10,0 L 5,10 z M 4,2 A 1,1 0 0 0 3,3 L 3,4 A 1,1 0 0 0 4,5 L 6,5 A 1,1 0 0 0 7,4 L 7,3 A 1,1 0 0 0 6,2 z"
            Fill="{DynamicResource {x:Static SystemColors.WindowBrushKey}}"
            Stretch="Uniform"
            Stroke="{DynamicResource {x:Static SystemColors.ActiveBorderBrushKey}}"
            StrokeThickness="4" />

        <TextBlock
            Margin="0,20,0,0"
            HorizontalAlignment="Center"
            FontSize="16"
            Text="Click+Drag to move ..." />

        <Button
            Margin="0,0,0,80"
            HorizontalAlignment="Center"
            VerticalAlignment="Bottom"
            Click="CloseButtonClick"
            Content="Close" />
    </Grid>
</Window>

HollowView.xaml.cs

public partial class HollowView
{
    public HollowView()
    {
        InitializeComponent();
        MouseLeftButtonDown += (s, e) => DragMove();
    }

    private void CloseButtonClick(object sender, System.Windows.RoutedEventArgs e)
    {
        Close();
    }
}

用法

private void btnShowHollowWindow_Click(object sender, RoutedEventArgs e)
{
    var hollowView = new HollowView
    {
        Width = 300,
        Height = 300,
        Owner = this,
        WindowStartupLocation = WindowStartupLocation.CenterOwner
    };

    hollowView.ShowDialog();
}

有关 WPF 中自定义窗口布局的更多详细信息,请查看我的博客文章


推荐阅读