The clock control : Custom Control « GUI Windows Forms « C# / CSharp Tutorial






using System;
using System.Collections;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Windows.Forms;


public class DigitalClock : System.Windows.Forms.UserControl {
    private System.Windows.Forms.Timer timer1;
    private System.ComponentModel.IContainer components;

    public DigitalClock() {
        this.components = new System.ComponentModel.Container();
        this.timer1 = new System.Windows.Forms.Timer(this.components);
        this.timer1.Enabled = true;
        this.timer1.Interval = 1000;
        this.timer1.Tick += new System.EventHandler(this.OnTick);
        this.Paint += new System.Windows.Forms.PaintEventHandler(this.OnPaint);
    }
    private void OnPaint(object sender,  System.Windows.Forms.PaintEventArgs e) {
        System.DateTime dt = System.DateTime.Now;
        String Text = dt.ToLongTimeString();
        e.Graphics.DrawString(Text, Font, new SolidBrush(ForeColor),ClientRectangle);
    }
    private void OnTick(object sender, System.EventArgs e) {
        this.Refresh();
    }
}
public class Form1 : System.Windows.Forms.Form {
    private System.Windows.Forms.Label label1;

    private DigitalClock clock= new DigitalClock();

    public Form1() {
        this.label1 = new System.Windows.Forms.Label();
        this.SuspendLayout();
        this.label1.Location = new System.Drawing.Point(16, 24);
        this.label1.Size = new System.Drawing.Size(128, 16);
        this.label1.Text = "Clock:";

        this.clock.Location = new System.Drawing.Point(16, 50);
        this.clock.Size = new System.Drawing.Size(128, 80);
        this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
        this.ClientSize = new System.Drawing.Size(292, 273);
        this.Controls.AddRange(new System.Windows.Forms.Control[] {
              this.label1,
              this.clock});
        this.ResumeLayout(false);
    }
    [STAThread]
    static void Main() {
        Application.Run(new Form1());
    }
}








23.56.Custom Control
23.56.1.Create your own component by subclassing System.ComponentModel.Component
23.56.2.Create controlCreate control
23.56.3.The clock control