窗体外观效果和通知窗口






4.35/5 (13投票s)
2005年7月11日
2分钟阅读

100311

7750
本文包含一个窗体,该窗体可用于为任何窗体,特别是通知/警报窗口提供淡入/淡出效果。
引言
后台进程、从托盘运行的应用程序和许多其他类型的应用程序通常需要向用户显示通知/警报。一个常见的例子是 Outlook 2003,它在系统托盘上方显示电子邮件通知。本文是关于一个基类 `TransDialog`,它派生自 `Form` 并为任何窗体添加淡入/淡出效果。它还包含一个通知窗体,该窗体派生自此 `TransDialog` 并在系统托盘上方显示通知。
使用代码
该项目包含以下三个窗体/类
TransDialog
- 派生自System.Windows.Forms.Form
并添加淡入效果。Notification
- 派生自TransDialog
并且实际上显示通知。Form1
- 驱动窗体,仅用于演示。
如果您只想添加淡入/淡出效果,您可以从 TransDialog
派生任何窗体,如下所示
public class Notification : TransDialog
{
#region Ctor, init code and dispose
public Notification()
: base(true)
{
InitializeComponent();
}
/* ... */
}
传递 true
到基类将确保当您在 Notification
窗体上调用 Close
时,TransDialog
将调用 Dispose
并进行清理。
TransDialog 如何工作
TransDialog
使用窗体的分层(不透明度)属性来添加淡入/淡出的效果。在窗体 Load
事件中,窗体的不透明度设置为 0(完全透明或不可见),并且启动一个计时器 m_clock
。变量 m_bShowing
设置为 true
。计时器设置为每 100 毫秒跳动一次。
private void TransDialog_Load(object sender, EventArgs e)
{
this.Opacity = 0.0;
m_bShowing = true;
m_clock.Start();
}
在每次 Tick
事件中,只要 m_bShowing
为 true
,不透明度就会增加,直到达到 1(完全不透明)。
if (m_bShowing)
{
if (this.Opacity < 1)
{
this.Opacity += 0.1;
}
else
{
m_clock.Stop();
}
}
这会产生淡入效果。
在窗体关闭事件中,m_bShowing
设置为 false
,窗体关闭被取消,并且计时器再次启动。但是,由于此时 m_bShowing
为 false
,不透明度会降低,直到达到 0(完全透明)。这会产生淡出效果。
private void TransDialog_Closing(object sender, CancelEventArgs e)
{
/* ... */
m_origDialogResult = this.DialogResult;
e.Cancel = true;
m_bShowing = false;
m_clock.Start();
/* ... */
}
Notification 如何工作
通知的淡入/淡出效果只需从 TransDialog
派生即可。为了在系统托盘上方正确的位置显示窗体,在 Load
事件处理程序中使用以下代码。
private void Notification_Load(object sender, System.EventArgs e)
{
/* ... */
int screenWidth = Screen.PrimaryScreen.WorkingArea.Width;
int screenHeight = Screen.PrimaryScreen.WorkingArea.Height;
this.Left = screenWidth - this.Width;
this.Top = screenHeight - this.Height;
/* ... */
}