{A}{S0}简介
我最喜爱的桌面小工具之一是/谷歌桌面工具栏,但因为谷歌的工作人员决定停止其发展,我决定建立它的一个克隆。
在寻找它的GUI,出现的第一个问题,是像菜单显示切换按钮。我GOOGLE了很多,如果没有平等的组成部分,但没有成功,所以我已经开始思考,我必须遵循开发一个组件具有相同的外观和感觉的方式寻求类似。
首选,自然,使用ToggleButton的,但也是这个组件没有直接提供的。NET,但只是作为一个COM组件。使用COM组件,如果没有必要,可以减少代码的清洁。一些测试表明,与切换般的感觉的一个组成部分,作为一个特殊的外观复选框。因此,我们可以开始编码..."守则"public partial class ButtonMenu : CheckBox
在构造函数中,我设立的基本面貌面向属性:{C}
使用CheckBox的基类赋予我的能力,以减少codenbsp的,我需要编写,以达到我的目标。唯一的代码,我需要添加特定菜单....把此菜单!private ContextMenuStrip menu=null;
public ContextMenuStrip Menu
{
get
{
return menu;
}
set
{
/*
* If menu != null then we have a menu to clean before to change
*/
if(menu!=null)
menu.Closed -= menu_Closed;
menu = value;
if(menu != null)
menu.Closed += menu_Closed;
}
}
使用属性给了我两个优点:我可以改变它在设计时我可以在一个简单的方法管理的添加和移除事件处理程序
的先例代码,我们已经介绍的方法menu_Closed。它是这样的:private bool frombutton = false;
void menu_Closed(object sender, ToolStripDropDownClosedEventArgs e)
{
/*
* Popup Menu closing... raise the button
*/
if(!frombutton)
Checked = false;
}
布尔标志frombutton,是用来检查菜单关闭的原因,在细节的真实,如果菜单已关闭按钮事件由于它是假的,如果它失去焦点封闭。主要方法是简单... ...之后,你已经明白显示方法的行为:private void DisplayMenu()
{
// No menu...
if (menu == null)
return;
Point offset = new Point();
switch (direction)
{
case ToolStripDropDownDirection.AboveLeft:
offset.X = menu.Width;
offset.Y = 0;
break;
case ToolStripDropDownDirection.AboveRight:
offset.X = this.Width-menu.Width;
offset.Y = 0;
break;
case ToolStripDropDownDirection.BelowLeft:
offset.X = menu.Width;
offset.Y = this.Height;
break;
case ToolStripDropDownDirection.BelowRight:
offset.X = this.Width - menu.Width;
offset.Y = this.Height;
break;
case ToolStripDropDownDirection.Default:
offset.X = (this.Width - menu.Width)/2;
offset.Y = this.Height;
break;
case ToolStripDropDownDirection.Left:
offset.X = 0;
offset.Y = 0;
break;
case ToolStripDropDownDirection.Right:
offset.X = this.Width;
offset.Y = 0;
break;
}
menu.Show(this, offset, direction);
在上面的代码,方向是在ToolStripDropDownDirection枚举值用一个标准的get / set方法对访问。使用
作为代码,还指示很简单,添加ButtonMenu组件后,你工具箱,拖动窗体上的设置菜单属性和属性页(或通过代码)。享受。编辑:我已经合并autoplacing BlackTigerAP(我做了一个小quot书面代码的情况下compressionquot,以减少代码复制我已经添加了一个新的公共财产ButtonMenuStyle风格从设计,平面和按钮样式之间切换。课程:public enum ButtonMenuStyle
{
Flat = 0,
Button = 1,
}