我正在开发一个自定义控件,继承自
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;
看起来控件的
SetFocus
处理程序上的 MouseDown
正是所需要的。毕竟,某些控件在实际单击场景之外获得“单击”事件,因此不应自动获得焦点。因此,如果您想从鼠标获取焦点,则必须仅通过单击鼠标来实现。