我自己写的:
procedure TForm4.Edit1KeyPress(Sender: TObject; var Key: Char); begin if not (Key in ['0' .. '9', '.', '-', #8, #10, #13]) then begin Key := #0; end else begin if Key = '-' then begin if not string(TEdit(Sender).Text).Contains('-') then begin //光标定位在第一个上 TEdit(Sender).SelStart := 0; end else begin Key := #0; end; end else if Key = '.' then begin if not string(TEdit(Sender).Text).Contains('.') then begin //光标定位在最后一个上 TEdit(Sender).SelStart := Length(TEdit(Sender).Text); end else begin Key := #0; end; end; end; end;
默认支持左右方向键
万一老师的博客:http://www.cnblogs.com/del/archive/2007/11/24/970893.html
//让 Edit 只接受数字 //方法1: procedure TForm1.Edit1KeyPress(Sender: TObject; var Key: Char); begin if not (Key in ['0'..'9']) then Key := Chr(0); end; //方法2: procedure TForm1.Edit1KeyPress(Sender: TObject; var Key: Char); begin if not (Byte(Key) in [48..57]) then // 0的 Ascii 是 48 Key := Chr(0); end; //方法3: procedure TForm1.Edit1KeyPress(Sender: TObject; var Key: Char); begin if not CharInSet(Key, ['1'..'5']) then Key := #0; end;
//Edit 文本的选择与光标位置 procedure TForm1.Button1Click(Sender: TObject); begin Edit1.SetFocus; //给于焦点 SendMessage(Edit1.Handle,EM_SETSEL,0,1); //选择第一个字符 SendMessage(Edit1.Handle,EM_SETSEL,0,-1); //全选 SendMessage(Edit1.Handle,EM_SETSEL,1,1); //光标移到第一个字符后面 SendMessage(Edit1.Handle,EM_SETSEL,0,0); //光标移到开始 SendMessage(Edit1.Handle,EM_SETSEL,-1,0); //光标移到开始 end;
//待续...