自定义控件分为三种

  1. 用户控件(UserControl):继承 System.Windows.Forms.UserControl,在设计中可组合多个WinForm的控件。
  2. 扩展控件 (Extend an existing control):继承现有控件,对该控件修改和增强功能。
  3. 自定义控件(Custom control):继承 System.Windows.Forms.Control,创建新的外观或功能控件,完全由开发者绘制控件的界面(通过重写`OnPaint`方法)。

绘制需要重写OnPaint方法后,通过PaintEventArgs获取画布后需要new画刷,再通过画布提供的方法去绘制相应形状。绘制图像通常需要坐标和长宽度,控件默认坐标在控件坐上角(0,0)如图:x正方向向右,y正方向向下。

画一个矩形:

   /// <summary>
   /// 绘制
   /// </summary>
   /// <param name="e"></param>
   protected override void OnPaint(PaintEventArgs e)
   {
       base.OnPaint(e);
       Graphics g = e.Graphics; //获取画布
       Brush brush = new SolidBrush(Color.Red);//获取画刷
       graphics.FillRectangle(brush, new Rectangle(10, 10, 5, 5));//在坐标x=10,y=10填充矩形
}

控件的OnPaint触发条件

  1. 控件或窗体首次显示时
  2.   控件或窗体大小调整时
  3. 控件或窗体从被遮挡状态恢复时
  4. 程序显式请求重绘时调用 Invalidate() 或 Refresh() 方法,可以强制控件或窗体重绘
  5.  窗口区域失效时:比如由于其他窗口移动导致当前窗口的部分区域需要重绘。

在封装自定义控件时候,通常需要提供自定义属性和自定义事件等等......

 private int timeCountDown=0 ;
 [Category("自定义属性")]
 [Description("设置倒计时的时间,单位秒")]
 public int TimeCountDown
 {
     get { return timeCountDown; }
     set
     {
         timeCountDown = value > 999999 ? 999999 : value; //最大277.7775 小时
         Invalidate();
         //重置计时器
         StartCountdownTimer();
     }
 }

性能上,通常在构造函数写入双缓冲:

 this.DoubleBuffered = true;  // 启用双缓冲

 this.SetStyle(ControlStyles.AllPaintingInWmPaint |
                       ControlStyles.UserPaint |
                       ControlStyles.OptimizedDoubleBuffer, true);
 

Logo

全面兼容主流 AI 模型,支持本地及云端双模式

更多推荐