這篇文章主要介紹了C# ToolStrip浮動工具欄的制作,可以上/下/左/右停靠,代碼在下面
關於浮動工具條的制作 其實阿捷給出的代碼已經相當詳細了:) 我這裡主要給出重寫的ToolStrip代碼段,增加了三個ToolStripPanel 代碼如下: public partial class MyToolStrip : ToolStrip { public MyToolStrip() { InitializeComponent(); this.EndDrag += new EventHandler(MyToolStrip_EndDrag); this.SizeChanged += new EventHandler(MyToolStrip_SizeChanged); } #region 漂浮狀態 public ToolStripFloatWindow FloatWindow { get; set; } private bool isFloating { get { return (FloatWindow != null); } } public ToolStripPanel TopToolStripPanel { get; set; } public ToolStripPanel BottomToolStripPanel { get; set; } public ToolStripPanel LeftToolStripPanel { get; set; } public ToolStripPanel RightToolStripPanel { get; set; } #endregion #region 漂浮實現 private void FloatWindow_LocationChanged(object sender, EventArgs e) { //當floatwindws的位置移動到 toolstrippanel中時,將this放置到 toolstripPanel上 if (this.FloatWindow == null) { return; } if (FloatWindow.HasCreated) { //主窗體位置 Point frmLoc = this.TopToolStripPanel.Parent.Location; //浮動工具條位置 Point toolBarLoc = FloatWindow.Location; if (toolBarLoc.Y - frmLoc.Y <= 0) //置於頂部StripPanel { this.FloatWindow.Controls.Remove(this); this.TopToolStripPanel.SuspendLayout(); this.TopToolStripPanel.Controls.Add(this); this.Location = this.TopToolStripPanel.PointToClient(toolBarLoc); this.TopToolStripPanel.ResumeLayout(); this.FloatWindow.Dispose(); this.FloatWindow = null; return; } if (toolBarLoc.X - frmLoc.X <= 0) //置於左邊StripPanel { this.FloatWindow.Controls.Remove(this); this.LeftToolStripPanel.SuspendLayout(); this.LeftToolStripPanel.Controls.Add(this); this.Location = this.LeftToolStripPanel.PointToClient(toolBarLoc); this.LeftToolStripPanel.ResumeLayout(); this.FloatWindow.Dispose(); this.FloatWindow = null; return; } if (toolBarLoc.X + FloatWindow.Width >= this.TopToolStripPanel.Parent.Width) //置於右邊StripPanel { this.FloatWindow.Controls.Remove(this); this.RightToolStripPanel.SuspendLayout(); this.RightToolStripPanel.Controls.Add(this); this.Location = this.RightToolStripPanel.PointToClient(toolBarLoc); this.RightToolStripPanel.ResumeLayout(); this.FloatWindow.Dispose(); this.FloatWindow = null; return; } if (toolBarLoc.Y + FloatWindow.Height >= this.TopToolStripPanel.Parent.Height) //置於底部StripPanel { this.FloatWindow.Controls.Remove(this); this.BottomToolStripPanel.SuspendLayout(); this.BottomToolStripPanel.Controls.Add(this); this.Location = this.BottomToolStripPanel.PointToClient(toolBarLoc); this.BottomToolStripPanel.ResumeLayout(); this.FloatWindow.Dispose(); this.FloatWindow = null; return; } } } private void MyToolStrip_EndDrag(object sender, EventArgs e) { Point screenPt = Cursor.Position; Point clientPt = this.TopToolStripPanel.Parent.PointToClient(screenPt); //浮動區域 Rectangle floatArea = new Rectangle(32, 32, //我這裡圖標大小調整為32*32 this.TopToolStripPanel.Parent.Width - 2 * 32, this.TopToolStripPanel.Parent.Height - 2 * 32); if (floatArea.Contains(clientPt)) //判斷移出時 &nb