1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 | class CheckBoxEx : CheckBox { public CheckBoxEx() { } public override string Text { get { return base.Text; } set { base.Text = value; Size size = TextRenderer.MeasureText(value, Font); if (Width < size.Width + ClientSize.Height) Width = size.Width + ClientSize.Height; } } public override Font Font { get { return base.Font; } set { base.Font = value; Size size = TextRenderer.MeasureText(Text, value); if (Width < size.Width + ClientSize.Height) Width = size.Width + ClientSize.Height; } } protected override void OnPaint(PaintEventArgs e) { int h = ClientSize.Height; Rectangle rc = new Rectangle(new Point(0, 0), new Size(h, h)); e.Graphics.Clear(Parent.BackColor); ControlPaint.DrawCheckBox(e.Graphics, rc, this.Checked ? ButtonState.Checked : ButtonState.Normal); SizeF size = e.Graphics.MeasureString(Text, Font); e.Graphics.DrawString(Text, this.Font, new SolidBrush(Color.Blue), new PointF(h, size.Height < h ? (h - size.Height) / 2 : 0)); } } |
因重設字型大小或顯示文字內容會影響CheckBox的呈現寬度,因此一併重載Text與Font屬性,當使用者更改這兩個屬性值,則要重新計算CheckBox的寬度,否則文字呈現可能會被截斷。
使用方法跟一般CheckBox一樣:
1 2 3 4 5 6 | CheckBoxEx check = new CheckBoxEx(); check.Location = new Point(40, 40); check.ClientSize = new Size(30, 30); check.Text = "Hello CheckBox"; check.Font = new System.Drawing.Font("新細明體", 18); Controls.Add(check); |
Keyword:Customize checkbox size
沒有留言:
張貼留言