Winform重绘单选、多选控件

前言

对于单选和多选框这两个控件的使用场景还是比较多的,但是在Winform中有一个很奇怪的现象:基本上所有带可选择功能的控件,这个选择框都不能单独调整大小,所以就会导致很多时候字体较大,但是选择框是真的小,特别是在现在高分辨率的屏幕下,甚至还得去找......如果是在触摸屏上使用的话,估计你已经抓狂了;

所以,在之前的文章中,有针对DataGridView的选择框做过一次重绘;这一篇就单独用来重绘下这两个控件,即RadioButtonCheckBox.

开发环境:.NET Framework版本:4.8

开发工具:Visual Studio 2022

实现步骤

  1. 首先去找四个好看的图标,分别对应RadioButtonCheckBox的选中/未选中状态(当然不想用图片也可以,比如自己画框或者使用图标库),然后将这些图片加入到资源文件中。

  2. 创建自定义控件,定义Checked属性 

private bool _checked = false;public bool Checked { get { return _checked; } set { _checked = value; Invalidate(); }
 
 
  1. 重写OnPaint事件,做以下处理

    rotected override void OnPaint(PaintEventArgs e)        {            base.OnPaint(e);            e.Graphics.SmoothingMode = SmoothingMode.AntiAlias;            e.Graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;            e.Graphics.CompositingQuality = CompositingQuality.HighQuality;            e.Graphics.TextRenderingHint = TextRenderingHint.ClearTypeGridFit;            SizeF textSize = e.Graphics.MeasureString(Text, Font);            SizeF imgSize = new SizeF(textSize.Height, textSize.Height);            float imgX = 5, imgY = (Height - imgSize.Height) / 2;            e.Graphics.DrawImage(Checked ? Properties.Resources.Check_check : Properties.Resources.Check_normal, imgX, imgY, imgSize.Width, imgSize.Height);            float textX = imgX + imgSize.Width + 5, textY = (Height - textSize.Height) / 2 + 2;            e.Graphics.DrawString(Text, Font, new SolidBrush(ForeColor), textX, textY);        }
 
  1. 重写OnClick事件

     protected override void OnClick(EventArgs e)        {            base.OnClick(e);            Checked = !Checked;        }
 
 
 
  1. 针对单选情况需要特殊处理,即在同一个容器中的时候,只能选中一个,所以RadioButtonOnClick事件如下

      protected override void OnClick(EventArgs e)        {            base.OnClick(e);            SetChecked();        }        private void SetChecked()        {            Checked = !Checked;            if (Parent != null && !(Parent is Form))            {                foreach (Control control in Parent.Controls)                {                    if (control is RadioEx radio)                    {                        radio.Checked = false;                    }                }                Checked = true;            }        }
 
 
 
  1. OnPaint事件中可以看到,选择框的大小是随着字体大小而调整的,所以只需要修改Font的属性即可

实现效果

Winform重绘单选、多选控件