为什么我的自定义控件没有获得自身的焦点?

问题描述 投票:0回答:1

我正在开发一个自定义控件,继承自

TCustomControl
。我重写了一些事件,例如
KeyDown
,以便我可以捕获键盘和鼠标输入。但是,无论出于何种原因,当用户单击它时,它都不会自动获得焦点。我必须在
SetFocus
事件中添加
MouseDown
,然后它才真正获得焦点。但我很确定我不必这样做。为什么会发生这种情况,如何修复它,以便它能够自行聚焦而无需手动调用
SetFocus

  • 自定义控件的
    TabStop
    设置为
    True
  • 控件的父窗体(以及所有窗体)将
    KeyPreview
    设置为
    False

我像这样定义这些方法:

type
  TMyControl = class(TCustomControl)
  ...
  protected
    procedure KeyDown(var Key: Word; Shift: TShiftState); override;
    procedure KeyUp(var Key: Word; Shift: TShiftState); override;
    procedure KeyPress(var Key: Char); override;
    procedure MouseDown(Button: TMouseButton; Shift: TShiftState;
      X, Y: Integer); override;
    procedure MouseMove(Shift: TShiftState; X, Y: Integer); override;
    procedure MouseUp(Button: TMouseButton; Shift: TShiftState;
      X, Y: Integer); override;
    ...
  end;

然后实施:

procedure TMyControl.KeyDown(var Key: Word; Shift: TShiftState);
begin
  inherited;
  ...
  Invalidate;
end;

procedure TMyControl.KeyPress(var Key: Char);
begin
  inherited;
  ...
  Invalidate;
end;

procedure TMyControl.KeyUp(var Key: Word; Shift: TShiftState);
begin
  inherited;
  ...
  Invalidate;
end;

procedure TMyControl.MouseDown(Button: TMouseButton; Shift: TShiftState; X,
  Y: Integer);
begin
  inherited;
  SetFocus; //<-- This shouldn't be necessary...?
  ...
  Invalidate;
end;

procedure TMyControl.MouseMove(Shift: TShiftState; X, Y: Integer);
begin
  inherited;
  ...
  Invalidate;
end;

procedure TMyControl.MouseUp(Button: TMouseButton; Shift: TShiftState; X,
  Y: Integer);
begin
  inherited;
  ...
  Invalidate;
end;
delphi focus vcl tcustomcontrol
1个回答
0
投票

看起来控件的

SetFocus
处理程序上的
MouseDown
正是所需要的。毕竟,某些控件在实际单击场景之外获得“单击”事件,因此不应自动获得焦点。因此,如果您想从鼠标获取焦点,则必须仅通过单击鼠标来实现。

© www.soinside.com 2019 - 2024. All rights reserved.