正在加载

调用Windows API实现C#窗体阴影

| 2008年5月8日星期四

做Service Master 1.7的时候,突然想起来我是不是也应该给这个朴素的软件加上一点花的东西,呵呵,于是,就觉得应该去做一个窗体的透明,此外还想实现带有阴影效果窗体,研究了一下WindowsAPI,最后觉得透明和淡入淡出完全可以不用WinAPI来实现的,API实现之后的结果跟修改Opacity属性的效果是完全一样的。只需要在窗体阴影中使用API实现。

这个是具体的WinAPI实现窗体阴影的效果


具体的代码如下

首先是WinAPI类,包装与调用WindowsAPI
[coolcode lang="cpp" download="WinAPI.cs"]
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;

namespace ServiceMaster
{
class WinAPI
{
[DllImport("user32.dll")]
public extern static IntPtr GetWindow();

[DllImport("user32.dll")]
public extern static bool SetLayeredWindowAttributes(IntPtr hwnd, uint crKey, byte bAlpha, uint dwFlags);
public static uint LWA_COLORKEY = 0x00000001;
public static uint LWA_ALPHA = 0x00000002;

#region 阴影效果变量
//声明Win32 API
[DllImport("user32.dll", CharSet = CharSet.Auto)]
public static extern int SetClassLong(IntPtr hwnd, int nIndex, int dwNewLong);
[DllImport("user32.dll", CharSet = CharSet.Auto)]
public static extern int GetClassLong(IntPtr hwnd, int nIndex);
[DllImport("user32.dll")]
public extern static uint SetWindowLong(IntPtr hwnd, int nIndex, uint dwNewLong);
[DllImport("user32.dll")]
public extern static uint GetWindowLong(IntPtr hwnd, int nIndex);
#endregion

public enum WindowStyle : int
{
GWL_EXSTYLE = -20
}

public enum ExWindowStyle : uint
{
WS_EX_LAYERED = 0x00080000
}

}
}

[/coolcode]

然后是窗体中的调用
[coolcode lang="cpp" download="MainForm.cs"]
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.ServiceProcess;
using System.IO;
namespace ServiceMaster
{
public partial class MainFrom : Form
{
public MainFrom()
{
InitializeComponent();
const int CS_DropSHADOW = 0x20000;
const int GCL_STYLE = (-26);
WinAPI.SetClassLong(this.Handle, GCL_STYLE, WinAPI.GetClassLong(this.Handle, GCL_STYLE) | CS_DropSHADOW);
}
protected override CreateParams CreateParams
{
get
{
CreateParams cp = base.CreateParams;

cp.Parent = WinAPI.GetWindow();
return cp;
}
}

private void SetWindowShadow(byte bAlpha)
{
WinAPI.SetWindowLong(this.Handle, (int)WinAPI.WindowStyle.GWL_EXSTYLE,
WinAPI.GetWindowLong(this.Handle, (int)WinAPI.WindowStyle.GWL_EXSTYLE) | (uint)WinAPI.ExWindowStyle.WS_EX_LAYERED);

WinAPI.SetLayeredWindowAttributes(this.Handle, 0, bAlpha, WinAPI.LWA_COLORKEY | WinAPI.LWA_ALPHA);
}
}
[/coolcode]

如果你喜欢本文,把它分享到 Twitter / 校内 / 鲜果 / Digg
或者把它收藏到 Delicious