DotNet2.0開發架構中提供的ToolStrip和ToolStripPanel控制項可以方便開發具有可停駐工具列功能的Windows應用程式, ToolStrip對象可以在各個ToolStripPanel間完成拖拽停靠,但是如果想實作類別似VS IDE 或Office中可以浮動的工具列必須藉助於DevExpress等一些第三方的控制項或編寫一定的代碼。 這裡介紹一種比較簡單的方法,只需繼承ToolStrip類即可實現上述的效果。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
namespace FloatingToolStrip
...{
public partial class MyToolStrip : ToolStrip
...{
public MyToolStrip()
...{
InitializeComponent();
this.EndDrag += new EventHandler(MyToolStrip_EndDrag);
this.SizeChanged += new EventHandler(MyToolStrip_SizeChanged);
}
public ToolStripFloatWindow FloatWindow
...{
get
...{
return this.floatWindow;
}
set
...{
floatWindow = value;
if (FloatWindow != null)
...{
floatWindow.LocationChanged += new EventHandler(floatWindow_LocationChanged);
floatWindow.FormClosing += new FormClosingEventHandler(floatWindow_FormClosing);
}
}
}
public bool isFloating
...{
get
...{
return (floatWindow != null);
}
}
private ToolStripPanel tsPanel;
public ToolStripPanel ToolStripPanel
...{
get
...{
return this.tsPanel;
}
set
...{
tsPanel = value;
}
}
#endregion
漂浮實現#region 漂浮實現
private void floatWindow_LocationChanged(object sender, EventArgs e)
...{
//當floatwindws的位置移動到 toolstrippanel中時,將this放置到 toolstripPanel上
if (this.floatWindow == null)
...{
return;
}
Point currentPt = new Point(floatWindow.Location.X, floatWindow.Location.Y);
Point minpt = this.tsPanel.PointToScreen(tsPanel.Location);
Point maxpt;
if(this.tsPanel.Height <= 20)...{
maxpt = new Point(minpt.X + this.tsPanel.Width, minpt.Y + 20);
}else...{
maxpt = new Point(minpt.X + this.tsPanel.Width, minpt.Y + this.tsPanel.Height);
}