如何控制在text文本框里只能字符,不能输入汉字

flyfly2008 2009-10-14 10:58:23
如题
...全文
306 11 打赏 收藏 转发到动态 举报
写回复
用AI写文章
11 条回复
切换为时间正序
请发表友善的回复…
发表回复
BATTLERxANGE 2009-10-14
  • 打赏
  • 举报
回复
   string s = e.KeyChar.ToString();
byte[] by = Encoding.Default.GetBytes(s);
if (by.Length == 2)
{
int ascii = by[0] * 256 + by[1] - 65536;
if (ascii <= -2050 && ascii >= -20319)
e.Handled = true;
else
e.Handled = false;
}

可以输入除了汉字以外的任意字符
龙宜坡 2009-10-14
  • 打赏
  • 举报
回复
最好再加上Leave事件处理,恢复Ime默认值

不过不加也没什么问题!

private void textBox1_Leave(object sender, EventArgs e)
{
textBox1.ImeMode = ImeMode.NoControl;//确保只输入英文
}
龙宜坡 2009-10-14
  • 打赏
  • 举报
回复
加两个事件

KeyPress和Enter


private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
//只有字母及控制键有效
if (!Char.IsLetter(e.KeyChar) && !Char.IsControl(e.KeyChar))
{
e.KeyChar = '\0';
}
}

private void textBox1_Enter(object sender, EventArgs e)
{
textBox1.ImeMode = ImeMode.Disable;//确保只输入英文
}
BATTLERxANGE 2009-10-14
  • 打赏
  • 举报
回复
汉字区间10进制 45217--63486

如果换成用asc参数取,就是: -2050 ~ -20319

根据这个来判断吧!
flyfly2008 2009-10-14
  • 打赏
  • 举报
回复
如何正则,说明白点,楼上的
liutong123 2009-10-14
  • 打赏
  • 举报
回复
[Quote=引用 3 楼 l171147904 的回复:]
通过 KEY 控制!

onkeypress

设定只输入 字母 

例子:
private void award_markTextEdit_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
{
int iKey = (int)e.KeyChar;
bool bValidate = true;

if(iKey == 45 || iKey == 46 || (iKey>=48 && iKey <=57) || iKey == 8)
{
bValidate = false;
}
if(bValidate)
{
// e.KeyChar = (char)0;
e.Handled = true;
}

}


具体 KEY 值为 字母的范围 百度下!
[/Quote]何必这么麻烦啊,用正则表达式不就行了嘛
l171147904 2009-10-14
  • 打赏
  • 举报
回复
通过 KEY 控制!

onkeypress

设定只输入 字母

例子:
private void award_markTextEdit_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
{
int iKey = (int)e.KeyChar;
bool bValidate = true;

if(iKey == 45 || iKey == 46 || (iKey>=48 && iKey <=57) || iKey == 8)
{
bValidate = false;
}
if(bValidate)
{
// e.KeyChar = (char)0;
e.Handled = true;
}

}


具体 KEY 值为 字母的范围 百度下!
wuyi8808 2009-10-14
  • 打赏
  • 举报
回复
汉字也是字符的一种啊.
flyfly2008 2009-10-14
  • 打赏
  • 举报
回复
UP
l171147904 2009-10-14
  • 打赏
  • 举报
回复
KeyPress 事件 足够,别的多余。

这时间 本身 就包含 两个事件
DOWN 和 leave 事件
l171147904 2009-10-14
  • 打赏
  • 举报
回复
用 正则表达式 也是 改个 IF 判断而已!

上网搜索下


private void award_markTextEdit_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
{
int iKey = (int)e.KeyChar;
bool bValidate = true;

if(iKey == 45 || iKey == 46 || (iKey>=48 && iKey <=57) || iKey == 8) //正则也值是改这地方
{
bValidate = false;
}
if(bValidate)
{
e.Handled = true;
}

}

110,561

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧