C#实现WinForm窗体逐渐显示效果

C#实现WinForm窗体逐渐显示效果,这个博客园里面已经有其它人已经实现了,原理很简单,就是通过定时改变窗体的透明度(从0到1,即透明度从完全透明到不透明),我这里也是按照这个思路来实现的,但是我做的这个窗体是可复用的,即其它窗体继承自它后,就能实现渐显效果,代码如下:

using System;
using System.ComponentModel;
using System.Windows.Forms; namespace TEMS.Forms
{
public partial class FormBase : Form
{
private Timer formTimer = null; /// <summary>
/// 获取Opacity属性
/// </summary>
[DefaultValue()]
[Browsable(false)]
public new double Opacity
{
get { return base.Opacity; }
set { base.Opacity = ; }
} public FormBase()
{
InitializeComponent();
formTimer = new Timer() { Interval = };
formTimer.Tick += new EventHandler(formTimer_Tick);
base.Opacity = ;
} private void formTimer_Tick(object sender, EventArgs e)
{
if (this.Opacity >= )
{
formTimer.Stop();
}
else
{
base.Opacity += 0.2;
}
} private void FormBase_Shown(object sender, EventArgs e)
{
formTimer.Start();
}
}
}

以下是自动生成的代码:

namespace TEMS.Forms
{
partial class FormBase
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null; /// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
} #region Windows Form Designer generated code /// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.SuspendLayout();
//
// FormBase
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(, );
this.Name = "FormBase";
this.Text = "FormBase";
this.Shown += new System.EventHandler(this.FormBase_Shown);
this.ResumeLayout(false); } #endregion
}
}

代码中我用NEW关键字覆盖了FORM类中的Opacity属性,使其只读并且不可编辑,有人可能会说这个属性的只读代码写得不规范,应该是去掉SET访问器或将SET设为私有,没错,标准的是应该这样做,而我为何不这样做呢?原因就是如果真正将属性设为私有,那么在其它窗体继承它的时候,由于我们一般都是先建一个标准窗体,标准窗体在创建时窗体的属性若有默认值的会自动生成初始化默认值,标准窗体创建后才将基类改为FormBase类,这样就会造成报错:Opacity是只读的,不能赋值,所以我们只可以让其外面看到是可读写,但实际子窗体的赋值不会生效,起到只读效果,当然了,如果你不觉得麻烦的话,你可以按标准属性设置,然后每建立一个窗体后,请先将Opacity的代码清除,然后再更改继承类,这样也是可以的。

使用就很简单了,与正常的窗体相同,在这里就不叙述了,大家可将以上代码复制到自己的项目中,便可直接使用。

其实通过以上代码的思路,我们可以设计通用的百叶窗切换效果的窗体基类,有空我会试着去实现这些功能,希望大家能支持,谢谢!

上一篇:POJ 1088 滑雪 解题报告


下一篇:mysql查询练习