視窗淡入淡出效果能顯著提升軟體的專業感與用戶體驗。Vista/Win7 以降系統原生支援 DWM 合成效果,此技巧主要適用於 XP 等舊版本系統,或需自定義動畫速率的場景。
private void ShowWin()
{
this.tsmiShowHide.Text = "隱藏";
this.SetWindowState();
this.Opacity = 0; // 起始完全透明
Timer tStart = new Timer();
tStart.Interval = 100; // 100ms 觸發一次
tStart.Tick += tStart_Tick;
tStart.Start();
}
private void HideWin()
{
this.tsmiShowHide.Text = "顯示";
Timer tClose = new Timer();
tClose.Interval = 100;
tClose.Tick += tClose_Tick;
tClose.Start();
}
void tStart_Tick(object sender, EventArgs e)
{
this.Opacity += 0.1; // 每次增加 10% 不透明度
if (this.Opacity >= 1)
{
((Timer)sender).Stop();
this.Focus(); // 完全顯示後獲取焦點
}
}
void tClose_Tick(object sender, EventArgs e)
{
this.Opacity -= 0.1; // 每次減少 10%
if (this.Opacity <= 0)
{
((Timer)sender).Stop();
this.Hide(); // 完全透明後隱藏視窗
}
}
= 1 / <= 0 而非 == 1,避免浮點誤差導致動畫不停止Dispose(),防止記憶體洩漏DoubleAnimation,WinForms 可用 AnimateWindow API(P/Invoke)獲得硬體加速雖技術含量不高,但視窗淡入淡出是提升軟體質感的「低成本高回報」細節。本文提供可直接落地的 WinForms 實現,兼顧 XP 相容性與代碼簡潔性。現代專案建議優先使用 WPF 動畫系統或系統級 API 獲得更佳效能與效果。