2013-06-04 31 views
8

我想製作一個簡單的應用程序,它是透明的,但保留「正常」邊框,關閉按鈕,最小化和最大化按鈕。帶有邊框的C#WPF透明窗口

我知道如何使用標準

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

使窗口透明的,但這種去除邊框和右上角的按鈕。我讀這個線程,

Transparent window with a border

哪種類型的給解決方案,但說真的,我只是希望能夠保持標準的邊界,這將是那裏,如果我沒有使窗口透明。我可以移動窗口,調整大小,關閉等等的方式......這可能嗎?

回答

6

我扔一起快速Transparancy Converter類based on this tutorial on Microsoft.com你可以使用這個目的:

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

namespace WpfApplication2 
{ 
    class TransparancyConverter 
    { 
     private readonly Window _window; 

     public TransparancyConverter(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); 
    } 
} 

一旦你有這樣的,透明的背景屬性添加到您的XAML和訂閱Window_Loaded事件,並調用MakeTransparent方法:

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

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

的屏幕截圖是以下:

Screenshot

+0

非常感謝我會玩它 –

+0

幾乎工作。看起來像它在窗口7中工作,但不是在窗口8中。任何建議?先謝謝你! –

+0

@StefanVasiljevic不要以爲你會在8上有太多的運氣,上面的代碼使用Aero,它不存在於Windows 8上可悲的是 – JMK

1

我會先看看背景顏色rgb(a)顏色中的(a)lpha設置。 Alpha設置設置對象顏色的不透明度。

雖然,我注意到,因爲我發佈了這個,所以在我之前有另一篇文章,看起來更簡潔,可能會更適合你。