Author: Xiao source code: using System;
Using System. Collections. Generic;
Using System. ComponentModel;
Using System. Drawing;
Using System. Data;
Using System. Text;
Using System. Windows. Forms; namespace TimeTextBoxControl
{
Public partial class TimeTextBoxControl: UserControl
{
Public TimeTextBoxControl ()
{
InitializeComponent ();
If (textBox1.Text. Equals (""))
{
TextBox1.Text = "00:00 ";
}
} Public string TimeText
{
Get {return textBox1.Text ;}
Set {textBox1.Text = value ;}
} Private void textBox1_KeyPress (object sender, KeyPressEventArgs e)
{
TimeFormat (sender, e );
String currStr1 = "";
String currstr2 = "";
Int index = textBox1.SelectionStart; // obtain the cursor position
If (e. KeyChar> = 48 & e. KeyChar <= 57) // you can specify whether the input is a number or another character.
{
If (index> = 0 & index <5) // you can specify the cursor position.
{
If (textBox1.SelectionStart = 2)
{
CurrStr1 = textBox1.Text. Substring (0, index) + ":";
Currstr2 = textBox1.Text. Substring (index + 2 );
Index ++;
}
Else
{
CurrStr1 = textBox1.Text. Substring (0, index );
Currstr2 = textBox1.Text. Substring (index + 1 );
}
TextBox1.Text = currStr1 + e. KeyChar. ToString () + currstr2;
}
TextBox1.SelectionStart = index + 1;
}
Else
{
E. KeyChar = Convert. ToChar (0 );
}
If (textBox1.Text. Length> = 5)
{
E. KeyChar = Convert. ToChar (0 );
}
}
// Determine whether the input time is in the 24-hour format
Private void timeFormat (object sender, KeyPressEventArgs e)
{
If (textBox1.SelectionStart = 0)
{
If (e. KeyChar <48 | e. KeyChar> 50)
{
E. KeyChar = Convert. ToChar (48 );
}
}
If (textBox1.SelectionStart = 1)
{
If (textBox1.Text. Substring (0, 1). Equals ("0 ")))
{
If (e. KeyChar <48 | e. KeyChar> 57)
{
E. KeyChar = Convert. ToChar (0 );
}
}
Else
{
If (e. KeyChar <48 | e. KeyChar> 52)
{
E. KeyChar = Convert. ToChar (0 );