C#中實現窗體的淡入淡出

之前一直在想如何在C#中實現窗體的淡入淡出效果。但是看到網上很多教程說的是利用計時器或者線程功能實現淡入淡出效果。代碼看起來有點小長。沒辦法呀,我這個人是比較懶的嘛。繼續查了查,還有一種利用一個很有問題的API實現的淡入淡出,效果也很一般。回過頭去看看MFC程序,想到了AnimateWindow函數。

The AnimateWindow function enables you to produce special effects when showing or hiding windows. There are four types of animation: roll, slide, collapse or expand, and alpha-blended fade.

1
2
3
4
5
BOOL AnimateWindow(
	HWND hwnd,
	DWORD dwTime,
	DWORD dwFlags
	);

其實查閱一下MSDN就知道了,我們這裡使用這個主要是設定一下時間和Flags就可以了。具體的參數可以參見MSDN

什麽?在C#沒有定義這些Flags?沒關係,我們手工定義一下就可以了。像我就自己寫了一個類:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
    public class FormEffects
    {
        public const Int32 AW_HOR_POSITIVE = 0x00000001;
        public const Int32 AW_HOR_NEGATIVE = 0x00000002;
        public const Int32 AW_VER_POSITIVE = 0x00000004;
        public const Int32 AW_VER_NEGATIVE = 0x00000008;
        public const Int32 AW_CENTER = 0x00000010;
        public const Int32 AW_HIDE = 0x00010000;
        public const Int32 AW_ACTIVATE = 0x00020000;
        public const Int32 AW_SLIDE = 0x00040000;
        public const Int32 AW_BLEND = 0x00080000;
        [System.Runtime.InteropServices.DllImport("user32.dll", CharSet = System.Runtime.InteropServices.CharSet.Auto)]
        public static extern bool AnimateWindow(
        IntPtr hwnd,   //   handle   to   window    
        int dwTime,   //   duration   of   animation    
        int dwFlags   //   animation   type    
        );
    }

因為寫的代碼問題,根本不用使用什麽using。如果你想簡化一下也簡單:using System.Runtime.InteropServices即可。唔,我的工作是VAX代勞的,所以無所謂啦。

使用的時候這樣就可以了:

1
2
3
4
5
6
7
8
9
	private void WelcomeForm_Load(object sender, EventArgs e)
        {
            FormEffects.AnimateWindow(this.Handle, 500, FormEffects.AW_BLEND);
        }
 
        private void WelcomeForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            FormEffects.AnimateWindow(this.Handle, 500, FormEffects.AW_HOR_NEGATIVE | FormEffects.AW_HIDE | FormEffects.AW_BLEND);
        }

其實C#這種高級語言,很多時候如果調用API的話,參見VC的代碼都成啊。= =|||

此条目发表在 技术交流 分类目录,贴了 , 标签。将固定链接加入收藏夹。

C#中實現窗體的淡入淡出》有 2 条评论

  1. 不許起名。 Windows Vista Google Chrome 4.0.213.1 说:

    跟爛鳥脫離關系的時候,已經把他媽的VS SQL這些東西給刪完了。

发表评论

电子邮件地址不会被公开。 必填项已用 * 标注

*

您可以使用这些 HTML 标签和属性: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">

:zzz :stop :stone :smile :oops: :love :hurt2 :hurt :hit :hide :freeze :evil2 :cry :blind :angel 注意: 评论者允许使用'@user空格'的方式将自己的评论通知另外评论者。例如, ABC是本文的评论者之一,则使用'@ABC '(不包括单引号)将会自动将您的评论发送给ABC。使用'@all ',将会将评论发送给之前所有其它评论者。请务必注意user必须和评论者名相匹配(大小写一致)。