我可以在WinForms中的ToolStripSplitButton上使用Checked状态吗?

时间:2016-02-23 06:25:45

标签: c# winforms c#-3.0 toolstripbutton

有没有办法在ToolStripSplitButton上有Checked状态?我想要一个带有Checked属性的ToolStripButton来确定是否在我的应用程序窗口中显示了一个叠加层。我的用户想要直接交互来控制叠加层的不透明度,为此我想象有一个分割按钮,其中辅助按钮打开一个滑块来控制不透明度。 (当然,这不是标准功能,但我有信心将它们放在一起)。

但是,ToolStripSplitButton没有Checked属性,因此我无法直接执行此操作。我尝试使用标准的ToolStripButton,旁边有一个单独的ToolStripSplitButton,DropDownButtonWidth = 11,Margin = -5,1,0,2,所以看起来它属于ToolStripButton。它看起来很好,但是要完成它们作为单个按钮的错觉,我需要让它们同时使用相同的VisualStyles.PushButtonState绘制 - 所以当鼠标悬停在其中任何一个上时它们都会变热。

首先,我尝试在两个按钮上使用MouseEnter和MouseLeave事件尝试更改其他按钮的背景颜色,但这没有任何效果。然后我尝试使用每个按钮的Paint事件尝试使用带有PushButtonState = Hot的ButtonRenderer.DrawButton渲染它们,但这似乎也没有工作,并且变得非常混乱。似乎必须有更好的方法!

是否有一个简单的,或至少是实用的解决方案?

编辑:我所追求的效果是这样的:

Combined Check button with split drop-down

2 个答案:

答案 0 :(得分:1)

我建议您创建自己的UserControl并将其用作ToolStripItem

toolStripMenuItem.DropDownItems.Add(new ToolStripControlHost(new OverlayControl()));

以下是OverlayControl的一个简单示例,该示例是从您的说明中推断出来的(我建议您使用UserControl创建一个真实的Designer)。

public class OverlayControl : UserControl
{
    private readonly CheckBox _checkBox = new CheckBox();
    private readonly TrackBar _trackBar = new TrackBar();

    public ToolStripExtended()
    {
        _checkBox.Text = "Overlay";
        BackColor = SystemColors.Window;
        _checkBox.AutoSize = true;
        _trackBar.AutoSize = true;
        var flowLayoutPanel = new FlowLayoutPanel {AutoSize = true, AutoSizeMode = AutoSizeMode.GrowAndShrink};
        flowLayoutPanel.Controls.AddRange( new Control[] { _checkBox, _trackBar });
        Controls.Add(flowLayoutPanel);
        AutoSize = true;
        AutoSizeMode = AutoSizeMode.GrowAndShrink;
        PerformLayout();
    }
} 

答案 1 :(得分:0)

我提出的解决方案是通过继承ToolStripSplitButton来创建我自己的按钮,添加我自己的Checked属性,然后在检查时手动绘制它:

/// <summary>
/// ToolStripSplitCheckButton adds a Check property to a ToolStripSplitButton.
/// </summary>
public partial class ToolStripSplitCheckButton : ToolStripSplitButton
{
    //==============================================================================
    // Inner class: ToolBarButonSplitCheckButtonEventArgs
    //==============================================================================

    /// <summary>
    /// The event args for the check button click event. To be able to use the OnCheckedChanged
    /// event, we must also record a dummy button as well as this one (hack).
    /// </summary>
    public class ToolBarButonSplitCheckButtonEventArgs : ToolBarButtonClickEventArgs
    {
        /// <summary>
        /// Constructor.
        /// </summary>
        /// <param name="split_button">The sender split check button</param>
        public ToolBarButonSplitCheckButtonEventArgs(ToolStripSplitCheckButton split_button)
            : base(new ToolBarButton("Dummy Button"))       // Hack - Dummy Button is not used
        {
            SplitCheckButton = split_button;
        }

        /// <summary>
        /// The ToolStripSplitCheckButton to be sent as an argument.
        /// </summary>
        public ToolStripSplitCheckButton SplitCheckButton { get; set; }
    }


    //==========================================================================
    // Construction

    public ToolStripSplitCheckButton()
    {
        m_checked = false;
        m_mouse_over = false;
    }


    //==========================================================================
    // Properties

    /// <summary>
    /// Indicates whether the button should toggle its Checked state on click.
    /// </summary>
    [Category("Behavior"),
    Description("Indicates whether the item should toggle its selected state when clicked."),
    DefaultValue(true)]
    public bool CheckOnClick { get; set; }

    /// <summary>
    /// Indictates the Checked state of the button.
    /// </summary>
    [Category("Behavior"),
    Description("Indicates whether the ToolStripSplitCheckButton is pressed in or not pressed in."),
    DefaultValue(false)]
    public bool Checked { get { return m_checked; } set { m_checked = value; } }


    //==========================================================================
    // Methods

    /// <summary>
    /// Toggle the click state on button click.
    /// </summary>
    protected override void OnButtonClick(EventArgs e)
    {
        if (CheckOnClick) {
            m_checked = !m_checked;
            // Raise the OnCheckStateChanged event when the button is clicked
            if (OnCheckChanged != null) {
                ToolBarButonSplitCheckButtonEventArgs args = new ToolBarButonSplitCheckButtonEventArgs(this);
                OnCheckChanged(this, args);
            }
        }
        base.OnButtonClick(e);
    }

    /// <summary>
    /// On mouse enter, record that we are over the button.
    /// </summary>
    protected override void OnMouseEnter(EventArgs e)
    {
        m_mouse_over = true;
        base.OnMouseEnter(e);
        this.Invalidate();
    }

    /// <summary>
    /// On mouse leave, record that we are no longer over the button.
    /// </summary>
    protected override void OnMouseLeave(EventArgs e)
    {
        m_mouse_over = false;
        base.OnMouseLeave(e);
        this.Invalidate();
    }

    /// <summary>
    /// Paint the check highlight when required.
    /// </summary>
    protected override void OnPaint(PaintEventArgs e)
    {
        base.OnPaint(e);
        if (m_checked) {
            // I can't get the check + mouse over to render properly, so just give the button a colour fill - Hack
            if (m_mouse_over) {
                using (Brush brush = new SolidBrush(Color.FromArgb(64, SystemColors.MenuHighlight))) {
                    e.Graphics.FillRectangle(brush, ButtonBounds);
                }
            }
            ControlPaint.DrawBorder(
                e.Graphics,
                e.ClipRectangle,            // To draw around the button + drop-down
                //this.ButtonBounds,        // To draw only around the button 
                SystemColors.MenuHighlight,
                ButtonBorderStyle.Solid);
        }
    }


    //==========================================================================
    // Member Variables

    // The delegate that acts as a signature for the function that is ultimately called 
    // when the OnCheckChanged event is triggered.
    public delegate void SplitCheckButtonEventHandler(object source, EventArgs e);
    public event SplitCheckButtonEventHandler OnCheckChanged;

    private bool m_checked;
    private bool m_mouse_over;
}

要使用此功能,请处理此按钮的OnCheckChanged事件。

然而,这有几个笨拙的黑客。为了能够为检查按钮引发OnCheckedChanged事件,除了实际按钮之外,事件参数还必须包括对未使用的虚拟按钮的引用。即使在尝试使用各种渲染器之后,我也无法将检查+鼠标放在渲染上与正常检查按钮完全相同,所以我只是绘制一个颜色叠加,这几乎是正确但不完全。