WinForms 內建 ToolStripContainer 僅支援上下左右四邊停靠,**不支援脫離容器成為獨立浮動視窗**。本文實作 MyToolStrip 繼承 ToolStrip,結合 ToolStripPanel 與自訂 ToolStripFloatWindow,實現:
public class MyToolStrip : ToolStrip
{
// 四邊停靠面板(由宿主表單指派)
public ToolStripPanel TopToolStripPanel { get; set; }
public ToolStripPanel BottomToolStripPanel { get; set; }
public ToolStripPanel LeftToolStripPanel { get; set; }
public ToolStripPanel RightToolStripPanel { get; set; }
// 浮動視窗參考
public ToolStripFloatWindow FloatWindow { get; private set; }
public bool IsFloating => FloatWindow != null;
public MyToolStrip()
{
EndDrag += OnEndDrag; // 拖曳結束:決定浮動或停靠
SizeChanged += OnSizeChanged;
}
// ------------------------------------------------------------
// 拖曳結束:在浮動區域 → 建立浮動視窗;在停靠區域 → 吸附面板
// ------------------------------------------------------------
private void OnEndDrag(object sender, EventArgs e)
{
Point screenPt = Cursor.Position;
Point clientPt = TopToolStripPanel.Parent.PointToClient(screenPt);
// 定義浮動允許區域(避開四邊停靠區)
var floatArea = new Rectangle(32, 32,
TopToolStripPanel.Parent.Width - 64,
TopToolStripPanel.Parent.Height - 64);
if (floatArea.Contains(clientPt))
{
// 建立浮動視窗
FloatWindow = new ToolStripFloatWindow(this);
FloatWindow.Location = screenPt;
FloatWindow.Show(TopToolStripPanel.Parent);
FloatWindow.LocationChanged += FloatWindow_LocationChanged;
}
else
{
// 吸附至最近的 ToolStripPanel(簡化:依座標判斷)
DockToNearestPanel(clientPt);
}
}
// ------------------------------------------------------------
// 浮動視窗移動時:若移入停靠區 → 自動吸附回面板
// ------------------------------------------------------------
private void FloatWindow_LocationChanged(object sender, EventArgs e)
{
if (FloatWindow == null || !FloatWindow.HasCreated) return;
Point frmLoc = TopToolStripPanel.Parent.Location;
Point toolBarLoc = FloatWindow.Location;
// 判斷四邊吸附條件
if (toolBarLoc.Y - frmLoc.Y <= 0) DockToPanel(TopToolStripPanel, toolBarLoc);
else if (toolBarLoc.X - frmLoc.X <= 0) DockToPanel(LeftToolStripPanel, toolBarLoc);
else if (toolBarLoc.X + FloatWindow.Width >= TopToolStripPanel.Parent.Width) DockToPanel(RightToolStripPanel, toolBarLoc);
else if (toolBarLoc.Y + FloatWindow.Height >= TopToolStripPanel.Parent.Height) DockToPanel(BottomToolStripPanel, toolBarLoc);
}
private void DockToPanel(ToolStripPanel panel, Point screenLoc)
{
if (panel == null) return;
FloatWindow.Controls.Remove(this);
panel.SuspendLayout();
panel.Controls.Add(this);
Location = panel.PointToClient(screenLoc);
panel.ResumeLayout();
FloatWindow.Dispose();
FloatWindow = null;
}
private void DockToNearestPanel(Point clientPt)
{
// 簡易最近邊緣判斷
var panels = new[] { TopToolStripPanel, BottomToolStripPanel, LeftToolStripPanel, RightToolStripPanel };
ToolStripPanel nearest = null;
int minDist = int.MaxValue;
foreach (var p in panels)
{
if (p == null) continue;
int dist = Math.Abs(p.PointToScreen(Point.Empty).X - clientPt.X) +
Math.Abs(p.PointToScreen(Point.Empty).Y - clientPt.Y);
if (dist < minDist) { minDist = dist; nearest = p; }
}
if (nearest != null)
{
nearest.SuspendLayout();
nearest.Controls.Add(this);
nearest.ResumeLayout();
}
}
private void OnSizeChanged(object sender, EventArgs e)
{
// 浮動時同步調整 FloatWindow 大小
if (IsFloating) FloatWindow.Size = this.Size;
}
}
public class ToolStripFloatWindow : Form
{
public ToolStripFloatWindow(ToolStrip owner)
{
FormBorderStyle = FormBorderStyle.SizableToolWindow;
ShowInTaskbar = false;
TopMost = true; // 浮動視窗置頂
Controls.Add(owner);
owner.Dock = DockStyle.Fill;
Size = owner.PreferredSize;
StartPosition = FormStartPosition.Manual;
}
public bool HasCreated => IsHandleCreated;
protected override void OnFormClosing(FormClosingEventArgs e)
{
// 關閉浮動視窗時,將 ToolStrip 移回原容器或銷毀
if (Controls.Count > 0)
{
var ts = Controls[0] as ToolStrip;
Controls.Remove(ts);
ts.Parent = null;
}
base.OnFormClosing(e);
}
}
public partial class MainForm : Form
{
private readonly ToolStripPanel _topPanel, _bottomPanel, _leftPanel, _rightPanel;
public MainForm()
{
InitializeComponent();
// 建立四邊 ToolStripPanel
_topPanel = new ToolStripPanel { Dock = DockStyle.Top, Height = 30 };
_bottomPanel = new ToolStripPanel { Dock = DockStyle.Bottom, Height = 30 };
_leftPanel = new ToolStripPanel { Dock = DockStyle.Left, Width = 30 };
_rightPanel = new ToolStripPanel { Dock = DockStyle.Right, Width = 30 };
Controls.AddRange(new Control[] { _topPanel, _bottomPanel, _leftPanel, _rightPanel });
// 建立工具列並指派面板
var toolStrip = new MyToolStrip
{
TopToolStripPanel = _topPanel,
BottomToolStripPanel = _bottomPanel,
LeftToolStripPanel = _leftPanel,
RightToolStripPanel = _rightPanel
};
toolStrip.Items.AddRange(new ToolStripItem[] {
new ToolStripButton("新增"),
new ToolStripButton("開啟"),
new ToolStripButton("儲存")
});
_topPanel.Controls.Add(toolStrip); // 預設停靠頂部
}
}
| 技術點 | 實作要點 |
|---|---|
| 拖曳啟動 | ToolStrip 內建 EndDrag 事件,無需手動處理滑鼠訊息 |
| 浮動視窗 | 繼承 Form,FormBorderStyle.SizableToolWindow + TopMost |
| 吸附判斷 | LocationChanged 事件 + 座標邊界比對 |
| 面板切換 | SuspendLayout/ResumeLayout 防止閃爍,PointToClient 座標轉換 |
| 資源釋放 | 浮動視窗關閉時 Dispose,ToolStrip 移回面板 |
AutoScaleMode 與 DeviceDpi 轉換。System.Windows.Interop 或第三方動畫庫。透過繼承 ToolStrip 並結合 ToolStripPanel、自訂浮動視窗,即可在 WinForms 中實現類似 Visual Studio / Office 的專業級工具列停靠體驗。核心邏輯集中於 EndDrag 與 LocationChanged 兩大事件,程式碼結構清晰、易於擴展。