表单keypreview不起作用

时间:2012-12-09 15:34:11

标签: forms delphi keypreview

我创建了mainform(自动创建表单)和Form1(可用表单)。 我用来调用form1的方法就像这样

procedure Tmainform.Button2Click(Sender: TObject);
var
f : Tform1;
begin
f:=Tform1.create(self);
f.parent:=Tabsheet1;
f.visible:=true;
f.align:=alClient;
end;

问题是为什么Form1中的KeyPreview不起作用,即使我已经激活他的KeyPreview是真的吗?

1 个答案:

答案 0 :(得分:2)

function TWinControl.DoKeyDown(var Message: TWMKey): Boolean;中,如果存在,则将呼叫委托给父。

程序

procedure TWinControl.KeyDown(var Key: Word; Shift: TShiftState);
begin
  if Assigned(FOnKeyDown) then FOnKeyDown(Self, Key, Shift);
end;
如果Form是父级

,则不会调用

function TWinControl.DoKeyDown(var Message: TWMKey): Boolean;
var
  ShiftState: TShiftState;
  Form, FormParent: TCustomForm;
  LCharCode: Word;
begin
  Result := True;
  { First give the immediate parent form a try at the Message }
  Form := GetParentForm(Self, False);
  if (Form <> nil) and (Form <> Self) then 
  begin
    //  >> -- the DoKeyDown of the parent (not of your form) will be called 
    if Form.KeyPreview and TWinControl(Form).DoKeyDown(Message) then
      Exit;
    { If that didn't work, see if that Form has a parent (ie: it is docked) }
    if Form.Parent <> nil then 
    begin
      FormParent := GetParentForm(Form);
      if (FormParent <> nil) and (FormParent <> Form) and FormParent.KeyPreview and
          TWinControl(FormParent).DoKeyDown(Message) then
        Exit;
    end;
  end;
......