利用 Form.Opacity 屬性(0.0 完全透明 ~ 1.0 完全不透明)搭配 Timer 元件,即可實現視窗淡入動畫。
public partial class FadeInForm : Form
{
private double _opacity = 0;
private readonly Timer _timer;
public FadeInForm()
{
InitializeComponent();
Opacity = 0; // 起始完全透明
_timer = new Timer { Interval = 50 };
_timer.Tick += Timer_Tick;
_timer.Start();
}
private void Timer_Tick(object sender, EventArgs e)
{
if (_opacity <= 1.0)
{
_opacity += 0.05;
Opacity = _opacity;
}
else
{
_timer.Stop();
_timer.Dispose();
}
}
}
private async void FadeInForm_FormClosing(object sender, FormClosingEventArgs e)
{
if (e.CloseReason == CloseReason.UserClosing)
{
e.Cancel = true; // 先取消關閉
_timer = new Timer { Interval = 30 };
_timer.Tick += (s, args) =>
{
_opacity -= 0.1;
Opacity = _opacity;
if (_opacity <= 0)
{
_timer.Stop();
_timer.Dispose();
FormClosing -= FadeInForm_FormClosing; // 移除事件避免遞迴
Close(); // 真正關閉
}
};
_timer.Start();
}
}
從螢幕右下角向上滑入,停留數秒後向下滑出消失。類似 Outlook 新郵件提醒、Windows 通知中心風格。
FormBorderStyle = NoneShowInTaskbar = falseTopMost = trueScreen.PrimaryScreen.WorkingArea)Timer 或 Task.Delay 配合 Location.Y 漸進調整public class SlideNotification : Form
{
private readonly Timer _slideTimer = new Timer();
private readonly Timer _stayTimer = new Timer();
private int _targetY;
private int _direction; // 1=上滑入, -1=下滑出
private const int Step = 10;
public SlideNotification(string message, int stayMs = 3000)
{
InitializeComponent();
lblMessage.Text = message;
Size = new Size(300, 100);
FormBorderStyle = FormBorderStyle.None;
ShowInTaskbar = false;
TopMost = true;
StartPosition = FormStartPosition.Manual;
}
public void ShowNotification()
{
Rectangle wa = Screen.PrimaryScreen.WorkingArea;
Location = new Point(wa.Right - Width, wa.Bottom); // 起始:畫面外右下
_targetY = wa.Bottom - Height; // 目標:工作區右下角
_direction = 1;
_slideTimer.Interval = 15;
_slideTimer.Tick += SlideTimer_Tick;
_slideTimer.Start();
Show();
}
private void SlideTimer_Tick(object sender, EventArgs e)
{
if (_direction == 1) // 滑入
{
Location = new Point(Location.X, Location.Y - Step);
if (Location.Y <= _targetY)
{
Location = new Point(Location.X, _targetY);
_slideTimer.Stop();
// 停留階段
_stayTimer.Interval = 3000;
_stayTimer.Tick += (s, args) => { _stayTimer.Stop(); StartSlideOut(); };
_stayTimer.Start();
}
}
else // 滑出
{
Location = new Point(Location.X, Location.Y + Step);
if (Location.Y >= Screen.PrimaryScreen.WorkingArea.Bottom)
{
_slideTimer.Stop();
Close();
}
}
}
private void StartSlideOut()
{
_direction = -1;
_slideTimer.Start();
}
}
若專案使用 WPF,建議改用 Storyboard + DoubleAnimation 操作 Opacity、TranslateTransform.Y,效能更好、語法更宣告式、支援 GPU 加速。