Winform使用Win7的透明效果
某天闲的蛋疼的时候翻《WPF揭秘》,看到里面提到整个Windows背景都是玻璃效果的窗体。《WPF揭秘》提供了一段代码,通过一个类GlassHelper封装了PInvoke过来的系统API。想看那段代码的猛击这里
既然是系统API,当然就不只是WPF专用了。拆开了GlassHelper,主要内容就是两个PInvoke签名:DwmExtendFrameIntoClientArea控制窗体的玻璃效果,DwmIsCompositionEnabled检测系统的桌面组合功能是否打开。MARGINS是DwmExtendFrameIntoClintArea需要的参数结构,表达的是窗口四周的边框。实现全玻璃背景,其实就是将有玻璃效果的窗体边框向内扩展,当MARGINS足够大之后,就全变成玻璃状态了。
PInvoke签名
public struct MARGINS
{
public int Left;
public int Right;
public int Top;
public int Bottom;
}
static extern void DwmExtendFrameIntoClientArea(IntPtr hwnd, ref MARGINS margins);
static extern bool DwmIsCompositionEnabled();
所以,要在Winform里实现玻璃效果,只要
OnLoad protected override void OnLoad(EventArgs e)
{
if (DwmIsCompositionEnabled())
{
margins = new MARGINS();
margins.Right = margins.Left = margins.Top = margins.Bottom = this.Width+this.Height;
DwmExtendFrameIntoClientArea(this.Handle, ref margins);
}
base.OnLoad(e);
}
以及
OnPaintBackgroud
protected override void OnPaintBackground(PaintEventArgs e)
{
base.OnPaintBackground(e);
if (DwmIsCompositionEnabled())
{
e.Graphics.Clear(Color.Black);
}
}
通过上面的代码,在重绘背景的时候清除原本要绘制的背景,将透明的窗体底层显示出来。
效果如下
页:
[1]