C# WinForm 实现窗体淡入淡出

有时候我们需要给窗体的打开和关闭添加点动画效果.最近正好有这类需求,于是研究了下窗体的淡入淡出,很简单就实现了,这里发表下成果,以供朋友们使用.

在Windows,有一个API,可以设置窗体的可见度,我的淡入淡出就是基于此实现.

要使用Windows API,首先在类的最上面引用下InteropServices命名空间,代码如下:

using  System.Runtime.InteropServices;

OK,然后在类里面,声明要用的系统API,以及定义几个常量:

[DllImport("user32.dll", EntryPoint = "GetWindowLong")]
public static extern Int32 GetWindowLong(IntPtr hwnd, int nIndex);
[DllImport("user32.dll", EntryPoint = "SetWindowLong")]
public static extern Int32 SetWindowLong(IntPtr hwnd, int nIndex, Int32 dwNewLong);
[DllImport("user32", EntryPoint = "SetLayeredWindowAttributes")]
public static extern int SetLayeredWindowAttributes(IntPtr Handle, int crKey, byte bAlpha, int dwFlags);
const int GWL_EXSTYLE = -20;
const int WS_EX_TRANSPARENT = 0x20;
const int WS_EX_LAYERED = 0x80000;
const int LWA_ALPHA = 2;

然后在窗体的Load事件里面,把窗体的扩展风格设置一下,如果不这么设置,那么对窗体的可见度设置就是无效的了:

SetWindowLong(this.Handle, GWL_EXSTYLE, GetWindowLong(Handle, GWL_EXSTYLE) | WS_EX_LAYERED);

然后就要用到SetLayeredWindowAttributes这个API了,它的第3个参数是窗体可见度(单位:byte),我们只要连续调用这个API,然后第3个参数缓缓增高,即可实现窗体淡入动画,参数值缓缓降低则淡出.

淡入我们做在窗体的Shown事件里,淡出做在FormClosing事件里,代码如下:

private void Form1_Shown(object sender, EventArgs e)
{
    Effect(true);
}
 
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
    Effect(false);
}
 
private void Effect(bool show=true)
{
    for (byte i = 0; i < byte.MaxValue; i++)
    {
        SetLayeredWindowAttributes(this.Handle, 0, (byte)(show ? i : byte.MaxValue - i), LWA_ALPHA);
        Thread.Sleep(2);
        Application.DoEvents();
    }
}

完成,运行看看吧~

原文地址:https://www.cnblogs.com/DragonStart/p/9491170.html