1:文本的初始化
private void Init()
{
textBoxX1.Text = "域名";//给文本赋值
textBoxX1.Tag = "域名";//文本的tag值
textBoxX1.ForeColor = Color.Silver;//设置文本框字体的颜色
textBoxX1.TextAlign = HorizontalAlignment.Center;//设置文本框文本居中
textBoxX2.Tag = "姓名";
textBoxX2.Text = "姓名";
textBoxX2.ForeColor = Color.Silver;
textBoxX2.TextAlign = HorizontalAlignment.Center;
this.textBoxX1.Leave += new System.EventHandler(this.textBox_Leave);//失去文本框的焦点事件
this.textBoxX1.Enter += new System.EventHandler(this.textBox_Enter);//获取文本框的焦点事件
this.textBoxX2.Leave += new EventHandler(textBox_Leave);
this.textBoxX2.Enter += new EventHandler(textBox_Enter);
}
2:获取文本框的焦点事件
/// <summary>
/// 文本获取焦点的事件
/// </summary>
/// <param name="sender">代表引发事件的控件</param>
/// <param name="e">代表引发事件的参数</param>
private void textBox_Enter(object sender, EventArgs e)
{
TextBoxX tb = (sender as TextBoxX);//获取引发的控件信息
if (tb.Text == tb.Tag.ToString())//判断点击的控件的文本值是否为初始化
{
tb.Text = "";//清空文本
tb.ForeColor = Color.Black;//改变文本字体的颜色
}
}
3:失去文本框的焦点事件
private void textBox_Leave(object sender, EventArgs e)
{
TextBoxX tb = (sender as TextBoxX);
if (tb.Text == "")
{
tb.Text = tb.Tag.ToString();
tb.ForeColor = Color.Silver;
}
}
4:
public class TextControlInit
{
//构造函数传入时间控件
public TextControlInit(MonthCalendarAdv mca)
{
mcTime = mca;
}
private MonthCalendarAdv mcTime;
/// <summary>
/// 绑定时间控件文本框的鼠标点击事件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public void txtTime_MouseClick(object sender, MouseEventArgs e)
{
if (mcTime.Visible)//如果时间控件是显示就结束
{
return;
}
TextBoxX tb = sender as TextBoxX;
if (tb.Text == tb.Tag.ToString ())//判断获取的控件的Tag值是否与当前的Text相等
{
tb.Text = "";
tb.ForeColor = Color.Black;
}
mcTime.Tag = tb;
mcTime.Visible = true;
}
public void txtTime_Leave(object sender, EventArgs e)
{
TextBoxX tb = sender as TextBoxX;
if (tb.Text == "")
{
tb.Text = tb.Tag.ToString();
tb.ForeColor = Color.Silver;
}
else
{
string beginTime = tb.Text.Trim();
try
{
DateTime dt = Convert.ToDateTime(beginTime);
}
catch (Exception)
{
tb.Text = DateTime.Now.ToShortDateString();
}
}
mcTime.Visible = false;
}
public void txtTime_Enter(object sender, EventArgs e)
{
if (mcTime.Visible)
{
return;
}
TextBoxX tb = sender as TextBoxX;
if (tb.Text == tb.Tag.ToString())
{
tb.Text = "";
tb.ForeColor = Color.Black;
}
mcTime.Tag = tb;
mcTime.Visible = true;
}
public void TextBox_Leave(object sender, EventArgs e)
{
TextBoxX tb = sender as TextBoxX;
if (tb.Text == "")
{
tb.Text = tb.Tag.ToString();
tb.ForeColor = Color.Silver;
}
}
public void TextBox_Enter(object sender, EventArgs e)
{
TextBoxX tb = sender as TextBoxX;
if (tb.Text == tb.Tag.ToString())
{
tb.Text = "";
tb.ForeColor = Color.Black;
}
}
public void mcTime_DateSelected(object sender, DateRangeEventArgs e)
{
TextBoxX tb = mcTime.Tag as TextBoxX;
tb.Text = e.Start.ToShortDateString();
if (tb.Text != "")
{
mcTime.Visible = false;
}
}
}