作者:肖肖
源代碼:
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;//獲取光標位置
if (e.KeyChar >= 48 && e.KeyChar <= 57)//判斷所輸入的是數字還是其他字符
{
if (index>=0 && index<5)//判斷光標位置
{
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);
}
}
//判斷輸入的時間是否為24小時制
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);