自定义控件


在WinForm项目上右键——>添加——>新建项——>找到Windows Forms ——>点击自定义控件——>命名——>添加——>找到定义的控件(命名.cs)——>双击打开——>删除其中的(命名.Designer.cs)的文件——>找到命名文件双击打开——>删除public partial class中的partial以及public MyButtom()
{
InitializeComponent();
}中的InitializeComponent();



1
using System; 2 using System.Collections.Generic; 3 using System.ComponentModel; 4 using System.Data; 5 using System.Drawing; 6 using System.Linq; 7 using System.Text; 8 using System.Threading.Tasks; 9 using System.Windows.Forms; 10 11 namespace WinForm测试 12 { 13 public class MyButton : Control 14 { 15 public MyButton() 16 { 17 18 } 19 20 protected override void OnPaint(PaintEventArgs pe) 21 { 22 //base.OnPaint(pe); 23 Graphics g = pe.Graphics; 24 25 if (backgroundImageM != null) //判断是否有背景图 26 { 27 g.DrawImage(backgroundImageM, this.ClientRectangle); //画出背景图参数1背景图,参数2默认的矩形 28 } 29 g.FillRectangle(new SolidBrush(backColorM), this.ClientRectangle); //画背景参数1实心的backColorM颜色的,参数2默认的矩形 30 g.DrawString(textM, fontM, new SolidBrush(FontMColor), this.ClientRectangle); //画文字参数1要画的文字,参数2文字的大小等,参数3文字的颜色,参数4默认的矩形 31 } 32 33 /// <summary> 34 /// 控件的默认图片 35 /// </summary> 36 private Image backgroundImageM = null; 37 [Description("控件的默认图片")] //在属性中点击此属性的提示 38 public Image BackgroundImageM 39 { 40 get { return backgroundImageM; } 41 set 42 { 43 backgroundImageM = value; 44 } 45 } 46 47 /// <summary> 48 /// 控件的背景色 49 /// </summary> 50 private Color backColorM = Color.Transparent; 51 [Description("控件的背景色")] 52 public Color BackColorM 53 { 54 get { return backColorM; } 55 set 56 { 57 backColorM = value; 58 } 59 } 60 61 /// <summary> 62 /// 用于显示文本的字体 63 /// </summary> 64 private Font fontM = new System.Drawing.Font("宋体", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134))); 65 [Description("用于显示文本的字体")] 66 public Font FontM 67 { 68 get { return fontM; } 69 set 70 { 71 fontM = value; 72 } 73 } 74 75 /// <summary> 76 /// 文字的颜色 77 /// </summary> 78 private Color fontMColor = Color.Black; 79 [Description("文字的颜色")] 80 public Color FontMColor 81 { 82 get { return fontMColor; } 83 set 84 { 85 fontMColor = value; 86 } 87 } 88 89 /// <summary> 90 /// 控件的文字提示 91 /// </summary> 92 private string textM = ""; 93 [Description("显示的文字")] 94 public string TextM 95 { 96 get { return textM; } 97 set 98 { 99 textM = value; 100 } 101 } 102 103 104 } 105 }
原文地址:https://www.cnblogs.com/jmy9/p/10813272.html