簡體   English   中英

C#WPF透明窗口帶邊框

[英]C# WPF transparent window with a border

我想制作一個透明的簡單應用程序,但保留“普通”邊框,關閉按鈕,最小化和最大化按鈕。

我知道如何使用標准使窗口透明

<Window
    WindowStyle="None"
    AllowsTransparency="True"
    Background="Transparent">
</Window>

但這會刪除邊框和右上角的按鈕。 我讀了這個帖子,

帶邊框的透明窗口

哪種解決方案,但實際上,我只是希望能夠保持標准邊框,如果我沒有使窗口透明。 我可以移動窗口,調整大小,關閉等等的方法......這可能嗎?

在Microsoft.com上將基於本教程的快速TransparencyConverter類匯集在一起您可以將其用於此目的:

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

namespace WpfApplication2
{
    class TransparencyConverter
    {
        private readonly Window _window;

        public TransparencyConverter(Window window)
        {
            _window = window;
        }

        public void MakeTransparent()
        {
            var mainWindowPtr = new WindowInteropHelper(_window).Handle;
            var mainWindowSrc = HwndSource.FromHwnd(mainWindowPtr);
            if (mainWindowSrc != null)
                if (mainWindowSrc.CompositionTarget != null)
                    mainWindowSrc.CompositionTarget.BackgroundColor = System.Windows.Media.Color.FromArgb(0, 0, 0, 0);

            var margins = new Margins
            {
                cxLeftWidth = 0,
                cxRightWidth = Convert.ToInt32(_window.Width) * Convert.ToInt32(_window.Width),
                cyTopHeight = 0,
                cyBottomHeight = Convert.ToInt32(_window.Height) * Convert.ToInt32(_window.Height)
            };

            if (mainWindowSrc != null) DwmExtendFrameIntoClientArea(mainWindowSrc.Handle, ref margins);
        }

        [StructLayout(LayoutKind.Sequential)]
        public struct Margins
        {
            public int cxLeftWidth;
            public int cxRightWidth;
            public int cyTopHeight;
            public int cyBottomHeight;
        }

        [DllImport("DwmApi.dll")]
        public static extern int DwmExtendFrameIntoClientArea(IntPtr hwnd, ref Margins pMarInset);
    }
}

完成此操作后,將Transparent Background屬性添加到XAML並訂閱Window_Loaded事件並調用MakeTransparent方法:

<Window etc etc Background="Transparent" Loaded="Window_Loaded">

private void Window_Loaded(object sender, RoutedEventArgs e)
{
    var transparencyConverter = new TransparencyConverter(this);
    transparencyConverter.MakeTransparent();
}

屏幕截圖如下:

截圖

我首先看一下背景顏色的rgb(a)顏色中的(a)lpha設置。 alpha設置設置對象顏色的不透明度。

雖然,我注意到,在我發布這篇文章之前,我的另一篇文章看起來更簡潔,可能更適合你。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM