| 功能 | 技術關鍵 |
| 展開動畫 | 背景執行緒 + `Control.Invoke` + 遞增 `Panel.Width` |
| 摺疊判斷 | `MouseMove` 事件 + `PointToClient(MousePosition)` 邊界檢測 |
| 鎖定狀態 | 移除 `MouseMove` 事件訂閱 / 布林旗標控制 |
| 防閃爍 | `DoubleBuffered = true` + `ControlStyles.AllPaintingInWmPaint` |
完整代碼實現
表單設計
// Form1.Designer.cs 關鍵控件
private Panel panelSidebar; // 側邊欄容器
private ListView listViewMenu; // 選單內容
private Button btnPin; // 鎖定/解鎖按鈕
private ToolStripButton btnTrigger; // 工具列觸發按鈕 (懸停展開)
核心邏輯
public partial class MainForm : Form
{
private const int ExpandedWidth = 245;
private const int CollapsedWidth = 0;
private const int AnimationSteps = 20;
private const int AnimationIntervalMs = 10;
private bool _isPinned = false;
private bool _isAnimating = false;
public MainForm()
{
InitializeComponent();
InitializeSidebar();
}
private void InitializeSidebar()
{
// Panel 設定
panelSidebar.Width = CollapsedWidth;
panelSidebar.Visible = false;
panelSidebar.Dock = DockStyle.Left;
// 防閃爍
typeof(Panel).InvokeMember("DoubleBuffered",
BindingFlags.SetProperty | BindingFlags.Instance | BindingFlags.NonPublic,
null, panelSidebar, new object[] { true });
// 觸發按鈕懸停展開
btnTrigger.MouseHover += BtnTrigger_MouseHover;
// 選單區域滑鼠移動檢測摺疊
listViewMenu.MouseMove += ListViewMenu_MouseMove;
// 鎖定按鈕
btnPin.Click += BtnPin_Click;
UpdatePinButtonUI();
}
// ========== 展開動畫 ==========
private void BtnTrigger_MouseHover(object sender, EventArgs e)
{
if (_isPinned || _isAnimating || panelSidebar.Visible) return;
AnimateSidebar(true);
}
private void AnimateSidebar(bool expand)
{
if (_isAnimating) return;
_isAnimating = true;
Task.Run(() =>
{
int start = expand ? CollapsedWidth : panelSidebar.Width;
int end = expand ? ExpandedWidth : CollapsedWidth;
int step = (end - start) / AnimationSteps;
if (step == 0) step = expand ? 1 : -1;
for (int w = start; expand ? w <= end : w >= end; w += step)
{
int clampedWidth = Math.Clamp(w, CollapsedWidth, ExpandedWidth);
SafeSetWidth(clampedWidth, expand && w == start); // 首幀顯示
Thread.Sleep(AnimationIntervalMs);
}
SafeSetWidth(end, expand);
_isAnimating = false;
// 展開完成後若未鎖定,延遲檢查是否需摺疊
if (expand && !_isPinned)
{
Task.Delay(2000).ContinueWith(_ => CheckAutoCollapse());
}
});
}
private void SafeSetWidth(int width, bool makeVisible)
{
if (panelSidebar.InvokeRequired)
{
panelSidebar.Invoke(new Action(SafeSetWidth), width, makeVisible);
}
else
{
panelSidebar.Width = width;
if (makeVisible && !panelSidebar.Visible) panelSidebar.Visible = true;
if (!expand && width == CollapsedWidth) panelSidebar.Visible = false;
}
}
// ========== 自動摺疊檢測 ==========
private void ListViewMenu_MouseMove(object sender, MouseEventArgs e)
{
if (_isPinned || _isAnimating) return;
Point clientPos = panelSidebar.PointToClient(Cursor.Position);
// 滑鼠超出 Panel 右邊界 + 容差
if (clientPos.X > panelSidebar.Width + 10)
{
AnimateSidebar(false);
}
}
private void CheckAutoCollapse()
{
if (_isPinned || _isAnimating) return;
Point clientPos = panelSidebar.PointToClient(Cursor.Position);
if (clientPos.X > panelSidebar.Width + 10 || !panelSidebar.ClientRectangle.Contains(clientPos))
{
AnimateSidebar(false);
}
}
// ========== 鎖定/解鎖 ==========
private void BtnPin_Click(object sender, EventArgs e)
{
_isPinned = !_isPinned;
UpdatePinButtonUI();
if (_isPinned)
{
// 鎖定:確保完全展開、移除自動摺疊邏輯
if (panelSidebar.Width < ExpandedWidth)
AnimateSidebar(true);
listViewMenu.MouseMove -= ListViewMenu_MouseMove;
}
else
{
// 解鎖:恢復自動摺疊、延遲檢查
listViewMenu.MouseMove += ListViewMenu_MouseMove;
Task.Delay(500).ContinueWith(_ => CheckAutoCollapse());
}
}
private void UpdatePinButtonUI()
{
btnPin.Text = _isPinned ? "📌" : "📍";
btnPin.ToolTipText = _isPinned ? "解除鎖定" : "鎖定側邊欄";
}
}
優化版:使用 Timer 替代 Thread.Sleep (UI 執行緒友善)
private System.Windows.Forms.Timer _animationTimer;
private int _targetWidth;
private int _step;
private void StartAnimation(bool expand)
{
if (_animationTimer == null)
{
_animationTimer = new System.Windows.Forms.Timer { Interval = AnimationIntervalMs };
_animationTimer.Tick += AnimationTimer_Tick;
}
_targetWidth = expand ? ExpandedWidth : CollapsedWidth;
_step = (_targetWidth - panelSidebar.Width) / AnimationSteps;
if (_step == 0) _step = expand ? 1 : -1;
if (expand && !panelSidebar.Visible) panelSidebar.Visible = true;
_animationTimer.Start();
}
private void AnimationTimer_Tick(object sender, EventArgs e)
{
int newWidth = panelSidebar.Width + _step;
bool reached = (_step > 0 && newWidth >= _targetWidth) || (_step < 0 && newWidth <= _targetWidth);
panelSidebar.Width = reached ? _targetWidth : newWidth;
if (reached)
{
_animationTimer.Stop();
if (!expand && _targetWidth == CollapsedWidth) panelSidebar.Visible = false;
if (!expand) return;
// 展開完成,設置自動摺疊檢查
if (!_isPinned)
{
Task.Delay(2000).ContinueWith(_ => CheckAutoCollapse());
}
}
}
現代化替代:WPF / WinUI 3 動畫
// 代碼後置
private void ToggleSidebar_Click(object sender, RoutedEventArgs e)
{
var animation = new DoubleAnimation
{
To = _isExpanded ? 0 : 245,
Duration = TimeSpan.FromMilliseconds(300),
EasingFunction = new QuadraticEase { EasingMode = EasingMode.EaseOut }
};
SidebarColumn.BeginAnimation(ColumnDefinition.WidthProperty, animation);
_isExpanded = !_isExpanded;
}
常見問題排查
| 問題 | 原因 | 解決 |
| 動畫卡頓/閃爍 | Thread.Sleep 阻塞、未雙緩衝、頻繁 Invalidate | 用 Timer、啟用 DoubleBuffered、批次更新 |
| 跨執行緒異常 | 背景執行緒直接操作 UI 控件 | Control.Invoke / BeginInvoke / SynchronizationContext |
| 摺疊後無法再展開 | Visible=false 導致 MouseHover 不觸發 | 觸發區域獨立於 Panel (如 ToolStripButton) |
| 鎖定狀態不同步 | 事件訂閱/取消訂閱時機錯誤 | 集中管理 `_isPinned` 旗標,統一入口 |
結語
WinForms 實現動態側邊欄的核心在於:**動畫循環與 UI 執行緒同步**、**滑鼠邊界檢測邏輯**、**狀態機管理 (展開/摺疊/鎖定)**。Timer 方案比 Thread+Invoke 更符合 WinForms 單執行緒模型。新專案強烈建議使用 WPF/WinUI 3/MAUI 等聲明式 UI 框架,動畫系統原生支援、效能更優、代碼更簡潔。
copyright ©
萬盛學電腦網 all rights reserved