添加复选框到按钮

时间:2015-03-09 10:12:05

标签: c# winforms

我想在Windows窗体按钮中添加一个复选框。目的是启用或禁用有关复选框状态按钮的配置。

示例图片:

enter image description here

2 个答案:

答案 0 :(得分:0)

  • 使用ToolStrip控件。

    • 添加按钮
    • 在每个按钮上将CheckOnClick属性设置为True
    • 添加你的图像(为了本演示的目的,我将使用表单范围的变量,但你可以使用ImageList或从文件系统中读取图像..无论如何)
    • 添加常用的点击处理程序以换出图像。

      '   Yes, this is VB, translate it if you need to.  
      Private config1Images As List(Of Image) ...
      
      Private Sub commonButtonClickHandler(sender As Object, e As EventArgs) Handles ConfigButton1.Click, ConfigButton2.Click, ConfigButton3.Click
          Dim button As ToolStripButton = sender
          Dim imageIndex As Int32 = 0
      
          If button.Checked Then
              imageIndex = 1
          End If
      
          If ConfigButton1 Is button Then
              button1.Image = config1Images(imageIndex)
          End If
          '   etc.
      End Sub  
      

      整个图片交换有点无意义,因为当按钮的.Checked属性= True时,ToolStripButton会为您更改背景颜色。

答案 1 :(得分:0)

您可以从现有的按钮类继承,只需使用VisualStyles类绘制并与CheckBox交互。我重写了MouseDown方法,以防止点击CheckBox区域触发按钮的click事件:

using System.Windows.Forms.VisualStyles;

public class ButtonWithCheckBox : Button {
  public bool OptionChecked { get; set; }

  protected override void OnMouseDown(MouseEventArgs e) {
    if (GetCheckBoxRectangle().Contains(e.Location)) {
      this.OptionChecked = !this.OptionChecked;
      this.Invalidate();
    } else {
      base.OnMouseDown(e);
    }
  }

  protected override void OnPaint(PaintEventArgs e) {
    base.OnPaint(e);
    CheckBoxRenderer.DrawCheckBox(e.Graphics,
      GetCheckBoxRectangle().Location,
      this.OptionChecked ? CheckBoxState.CheckedNormal : CheckBoxState.UncheckedNormal);
  }

  private Rectangle GetCheckBoxRectangle() {
    Rectangle result = Rectangle.Empty;
    using (Graphics g = this.CreateGraphics()) {
      Size sz = CheckBoxRenderer.GetGlyphSize(g, CheckBoxState.UncheckedNormal);
      result = new Rectangle(new Point(this.ClientSize.Width - (sz.Width + 8), 8), sz);
    }
    return result;
  }
}

结果:

enter image description here