Tech-Note For DKMILAN™

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

五月 7th, 2008 · No Comments

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

这个是具体的WinAPI实现窗体阴影的效果
2008-5-8-0000.png

具体的代码如下

首先是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 = 0×00000001;
public static uint LWA_ALPHA = 0×00000002;

#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 = 0×00080000
}

}
}

[/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 = 0×20000;
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]

Share :
  • Digg
  • del.icio.us
  • blogmarks
  • Fleck
  • Gwar
  • Haohao
  • Simpy
  • Spurl

Tags: .Net编程

0 responses so far ↓

  • There are no comments yet...Kick things off by filling out the form below.

Leave a Comment


为了防止恶意的垃圾评论脚本,请输入以下图片里面的数学方程式的答案。
防垃圾评论问题