C# WinForm给ToolStrip工具栏扩展一个CheckBox单选框类型按钮的方法

    [ToolStripItemDesignerAvailability(ToolStripItemDesignerAvailability.ToolStrip)]
    public partial class ToolStripCheckBox : ToolStripItem
    {
        private bool IsChecked = false;

        public bool HasChecked
        {
            get
            {
                return IsChecked;
            }
            set
            {
                IsChecked = value;
                this.Invalidate();
            }
        }

        public ToolStripCheckBox()
        {
            InitializeComponent();
        }

        public override Size GetPreferredSize(Size constrainingSize)
        {
            base.GetPreferredSize(constrainingSize);
            Size preferredSize = base.GetPreferredSize(constrainingSize);
            preferredSize.Width += 13; 
            return preferredSize;
        }

        protected override void OnClick(EventArgs e)
        {
            IsChecked = !IsChecked;
            base.OnClick(e);
        }

        protected override void OnPaint(PaintEventArgs e)
        {
            if (base.Owner != null)
            {
                Point pLocation = new Point(e.ClipRectangle.X, e.ClipRectangle.Height / 2 - (13 / 2));
                Size txtSize = TextRenderer.MeasureText(this.Text, this.Font);
                Rectangle rectText = new Rectangle(pLocation.X + 13, pLocation.Y, txtSize.Width, txtSize.Height);
                CheckBoxState chkState = IsChecked ? CheckBoxState.CheckedNormal : CheckBoxState.UncheckedNormal;
                CheckBoxRenderer.DrawCheckBox(e.Graphics, pLocation, rectText, this.Text, this.Font, false, chkState);
            }
            
        }

    }

  

posted @ 2024-06-24 09:49  LuoCore  阅读(15)  评论(0编辑  收藏  举报