Delphi中限制文本框(TEdit)只能輸入數字 (軟件技術) |
|
|
 |
procedure Tform1.Edit1KeyPress(Sender: TObject; var Key: Char); var edt: TEdit; str, strL, strR: string; p: integer; begin // 獲取當前文本內容, 注意要去掉選中部分(因為會被改寫). edt := TEdit(Sender); str := edt.text; if Length(edt.SelText) <> 0 then begin strL := LeftStr(edt.text, edt.SelStart); strR := RightStr(edt.text, Length(edt.text) - edt.SelStart - edt.SelLength); str := strL + strR; end; // 限制輸入數字/小數點/退格鍵 if not (Key in [#8, #13, #127, '.', '-', '0'..'9']) then Key := #0; //限制只能輸入一個小數點 if Key = '.' then begin p := Pos('.', edt.Text); if p > 0 then Key := #0; end; //限制只能在第一位輸入且只能輸入一個'-'號 if Key = '-' then begin if edt.SelStart > 0 then Key := #0; p := Pos('-', edt.Text); if p > 0 then Key := #0; end; end;
//要uses StrUtils單元 如果程序里有很多的TEdit要做此限制,當然不必給每個控件寫代碼,把事件指定到同一個過程就行了。 |
|