一个基本的选择器风格下拉工具栏按钮






2.22/5 (5投票s)
2005年5月13日
2分钟阅读

80383

479
本文档展示了如何实现一个基本的、选择器式下拉工具栏按钮。

引言
本文档展示了如何实现一个基本的、选择器式下拉工具栏按钮。 我觉得很奇怪,Visual Studio .NET 中没有这种简单的控件,尽管它几乎存在于每个 Windows 应用程序中。
最接近的实现是一个下拉按钮,看起来像这样

如果按钮的目的是双重的(执行某些操作以及呈现选择),这很好,但是有时你只想向用户呈现一个选择。 一个很好的例子是在 Windows 文件资源管理器中找到的视图配置选择器按钮。 在这种情况下,让用户点击按钮毫无意义。
Using the Code
这个控件被实现为一个 UserControl,可以包含在任何 C# Windows 项目中。 要使用该控件,只需将其拖放到你的表单上,并将其放置在已停靠的工具栏之上。 你需要在表单上拥有一个 ContextMenu 和一个 ImageList,它们可以在控件的属性表中与控件关联。

实现该按钮的代码非常简单——尽管花了一段时间才弄对…… 关键是使用 MouseDown 事件来显示上下文菜单,并使用控件的 Paint 事件将按钮的“Pushed”状态设置为 'false',当菜单消失时。 为了强制 Paint 事件触发,你必须在显示上下文菜单之前调用控件上的 Invalidate()。
private void On_toolBar_MouseDown(object sender, 
                    System.Windows.Forms.MouseEventArgs e)
{
    // Do nothing if there is no context menu
    if (this.m_contextMenu == null)
    {
        return;
    }
    // Ensure we clicked on the toolbar button
    if (!this.w_toolBarButton.Rectangle.Contains(new 
                     System.Drawing.Point(e.X,e.Y)))
    {
        return;
    }
    // Bring up the context menu
    if (!this.w_toolBarButton.Pushed)
    {
        this.w_toolBarButton.Pushed = true;
        this.ToolBarContextMenu.Show(this.w_toolBar, 
                    new System.Drawing.Point(0,22));
        this.Invalidate();
    }
}
private void On_ToolbarDropDownButton_Paint(object sender, 
                    System.Windows.Forms.PaintEventArgs e)
{
    this.w_toolBarButton.Pushed = false;
}
许可证
本文未附加明确的许可证,但可能在文章文本或下载文件本身中包含使用条款。如有疑问,请通过下面的讨论区联系作者。
作者可能使用的许可证列表可以在此处找到。
