procedure TForm1.FormCreate(Sender: TObject);
var
i:integer;
begin
for i:=0 to ComponentCount-1 do
if Components[i] is TEdit then
(Components[i] as TEdit).OnKeyPress:=EditKeyPress;
end;
procedure TForm1.EditKeyPress(Sender: TObject; var Key: Char);
var
Index:integer;
begin
if key=#13 then
begin
if ActiveControl.ComponentIndex < ComponentCount-1 then
Index:=ActiveControl.ComponentIndex+1
else
Index:=ComponentCount-1;
while (not (Components[Index] is TEdit)) and (Index < ComponentCount) do
begin
Index:=Index+1;
end;
(Components[Index] as TEdit).SetFocus;
(Components[Index] as TEdit).SelectAll;
end;
end;
这里我们利用了窗体的ActiveControl属性,它代表当前获得焦点的输入文本框;ComponentIndex属性代表了窗体控件放置的次序,也作为本方法中输入框获得焦点的顺序的参考。这个例子所使用方法的难点在于窗体上可以获得焦点的控件也许不止文本框,还有按钮、列表框、复选框等等,如何区分它们需要用到Delphi的运行时信息(RTTI)。另外,该方法有一个局限就是获得焦点的顺序和设计时控件放置的顺序相关。