在我的程序里面有这么一段:
private void period_tb_KeyPress(object sender, KeyPressEventArgs e)
{
e.Handled = (e.KeyChar < '0' || e.KeyChar > '9' || period_tb.Text.Length > 1);
if (e.KeyChar == (Char)Keys.Back)
{
e.Handled = false;
}
}
注: period_tb为TextBox用来控制最多只输入2位0-9的数字, 现在我的问题是, 当这个TextBox输入2位数字时, 我想双击这个TextBox来选中里面的Text(或者用鼠标将里面的Text全选), 然后就填上另外的数字, 但此时的TextBox已经被我控制不能再输入任何东西了(当然, 除了BackSpace), 大家有什么办法能让我在选中的情况下自由的输入其他数字呢?
private void period_tb_KeyPress(object sender, KeyPressEventArgs e)
{
e.Handled = (e.KeyChar < '0' || e.KeyChar > '9' || period_tb.Text.Length > 1);
if (e.KeyChar == (Char)Keys.Back)
{
e.Handled = false;
}
}
注: period_tb为TextBox用来控制最多只输入2位0-9的数字, 现在我的问题是, 当这个TextBox输入2位数字时, 我想双击这个TextBox来选中里面的Text(或者用鼠标将里面的Text全选), 然后就填上另外的数字, 但此时的TextBox已经被我控制不能再输入任何东西了(当然, 除了BackSpace), 大家有什么办法能让我在选中的情况下自由的输入其他数字呢?
private void txtSerialNo_TextChanged(object sender, EventArgs e)
{
string itemValue = txtSerialNo.Text.ToString();
if (IsNumeric(itemValue) == true)
{
ds.Tables["Dept"].Rows[bs.Position]["SerialNo"] = int.Parse(txtSerialNo.Text.ToString().Trim());
}
else
{
txtSerialNo.Text = "";
}
} private static bool IsNumeric(string itemValue)
{
return (IsRegEx("^(-?[0-9]*[.]*[0-9]{0,3})$", itemValue));
} private static bool IsRegEx(string regExValue, string itemValue)
{ try
{
Regex regex = new System.Text.RegularExpressions.Regex(regExValue);
if (regex.IsMatch(itemValue)) return true;
else return false;
}
catch (Exception)
{
return false;
}
finally
{
}
}
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (this.textBox1.SelectionLength == 0)
{
e.Handled = (e.KeyChar < '0' || e.KeyChar > '9' || textBox1.Text.Length > 1);
if (e.KeyChar == (Char)Keys.Back)
{
e.Handled = false;
}
}
}
private void Form1_Load(object sender, System.EventArgs e)
{
period_tb.MaxLength = 2;
}
private void period_tb_KeyPress(object sender, KeyPressEventArgs e)
{
e.Handled = (e.KeyChar < '0' || e.KeyChar > '9');
if (e.KeyChar == (Char)Keys.Back)
{
e.Handled = false;
}
}
禁止粘贴可以用以下这个方法,跟前面的一起用就行了: public const int WM_PASTE = 0x0302;//粘貼消息 protected override void WndProc(ref Message m)
{
if (m.Msg != WM_PASTE) base.WndProc(ref m);
}
用Leave事件不好,Leave事件是焦点离开的时候才会有效的, 但我的情况不是这样, 焦点并没有离开period_tb, 呵呵