//让 Edit 只接受数字,通过编辑Edit控件的onKeyPress事件实现
//方法1:

unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls;

type
  TForm1 = class(TForm)
    Edit1: TEdit;
    Button1: TButton;
    procedure Edit1KeyPress(Sender: TObject; var Key: Char);
    procedure Button1Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

procedure TForm1.Edit1KeyPress(Sender: TObject; var Key: Char);
begin
  if not (Key in ['0'..'9']) then   //如果不是输入数字,
  Key:=Char(0);                     //将当作没输入字符处理
end;

procedure TForm1.Button1Click(Sender: TObject);  //清空
begin
Edit1.Clear;
end;

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;

unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls;

type
  TForm1 = class(TForm)
    Edit1: TEdit;
    Button1: TButton;
    Edit2: TEdit;
    Button2: TButton;
    Button3: TButton;
    Button4: TButton;
    Button5: TButton;
    procedure Button1Click(Sender: TObject);
    procedure Button2Click(Sender: TObject);
    procedure Button3Click(Sender: TObject);
    procedure Button4Click(Sender: TObject);
    procedure Button5Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

procedure TForm1.Button1Click(Sender: TObject);
begin
  Edit2.SetFocus;
  SendMessage(Edit2.Handle,EM_SETSEL,0,1); //选择第一个字符
end;

procedure TForm1.Button2Click(Sender: TObject);
begin
  Edit2.SetFocus;
  SendMessage(Edit2.Handle,EM_SETSEL,0,-1); //全选
end;

procedure TForm1.Button3Click(Sender: TObject);
begin
  Edit2.SetFocus;
  SendMessage(Edit2.Handle,EM_SETSEL,1,1); //光标移到第一个字符后面
end;

procedure TForm1.Button4Click(Sender: TObject);
begin
  Edit2.SetFocus;
  SendMessage(Edit2.Handle,EM_SETSEL,0,0); //光标移到开始
end;

procedure TForm1.Button5Click(Sender: TObject);
begin
  Edit2.SetFocus;
  SendMessage(Edit2.Handle,EM_SETSEL,-1,0); //光标移到最后一个字符后面
end;

end.

 

 

 

posted on 2010-10-29 20:05  巅枫  阅读(637)  评论(0编辑  收藏  举报