delphi7的TEdit编辑框只允许输入1个字符(键盘上的字母、特殊符号等包括汉字)

如果设置MaxLength为1,则输入不了汉字(声明为string的汉字Length为2),
MaxLength设为2,则可以输入两个字母或特殊字符。
现要求edit只能输入一个汉字、一个字母、一个特殊符号
最新回答
雪紫∮冰雨

2024-04-14 06:42:25

直接判断有没有汉字啊,有就长度为2,没有就长度为1
//1,函数代码
{
判断字符串是否包含汉字
// judgeStr:要判断的字符串
//posInt:第一个汉字位置
}
function TForm2.IsHaveChinese(judgeStr: string; var posInt: integer): boolean;
var
p: PWideChar; // 要判断的字符
count: integer; // 包含汉字位置
isHave: boolean; // 是否包含汉字返回值
begin
isHave := false; // 是否包含汉字返回值默认为false
count := 1; // 包含汉字位置默认为1
p := PWideChar(judgeStr); // 把要判断字符串转换

// 循环判断每个字符
while p^ <> #0 do
begin
case p^ of
#$4E00 .. #$9FA5:
begin
isHave := true; // 设置是否包含汉字返回值为true
posInt := count; // 设置包含汉字位置
break; // 退出循环
end;
end;
Inc(p);
Inc(count); // 包含汉字位置递增
end;
result := isHave;
end;

//2,例子:

procedure TForm2.Button3Click(Sender: TObject);
var
testStr1, testStr2: string;
posInt: integer;
begin
testStr1 := '12345';
testStr2 := '123汉字45';

if self.IsHaveChinese(testStr1, posInt) = true then
begin
ShowMessage(testStr1 + ' 包含汉字 :' + inttostr(posInt));
end
else
begin
ShowMessage(testStr1 + ' 不包含汉字');
end;

if self.IsHaveChinese(testStr2, posInt) = true then
begin
ShowMessage(testStr2 + ' 包含汉字 :' + inttostr(posInt));
end
else
begin
ShowMessage(testStr2 + ' 不包含汉字');
end;
end;
丶小嘴灬乱亲

2024-04-14 11:27:41

我这里Delphi2007测试TEdit的MaxLength=1
可以输入一个完整的汉字,

你说D7不能的话,可以试试这两个方法
1。用TNT控件,TNT用的UNICODE字符集一个汉字一个字母长度都是1
2。用代码控制
OnChange事件
if length(widestring((Sender as TEdit).text))>=1 then
(Sender as TEdit).text:=widestring((Sender as TEdit).text)[1];
花寂月

2024-04-14 16:40:24

procedure TForm1.Edit1KeyPress(Sender: TObject; var Key: Char);
begin
if not (Key in ['a'..'z','0'..'9','A'..'Z','`','~','!','@','#','$','%','^','&','*','(',')','_','+','/','*','-','.',',','?','"','|','{','}'])then
begin
Edit1.MaxLength :=2;
end
else
begin
Edit1.MaxLength := 1;
end;
end;
楼主望采纳