如果您的 focusObserver 类可以是 TWinControl 的后代,那么您可以这样做:
TFocusObserver = class( TWinControl )
procedure CMFocusChanged(var Message: TCMFocusChanged); message CM_FOCUSCHANGED;
end;
和
procedure TFocusObserver.CMFocusChanged(var Message: TCMFocusChanged);
var
LControl: TWinControl;
begin
LControl := TWinControl(Message.Sender);
if LControl <> nil then
begin
form1.Caption := lControl.Name;
end;
end;
这里的主要思想是观看CM_FOCUSCHANGED
。
第二种方法:
注册控件时,您将其替换为WindowProc
. 这是一个小代码片段:
TRegisteredComp = class
private
fControl: TControl;
fowndproc: TWndMethod;
procedure HookWndProc(var Message: TMessage);
public
constructor Create( c: TControl );
destructor Destroy; override;
end;
TFocusObserver = class
private
l: TList;
public
constructor Create;
destructor Destroy; override;
procedure reg( c: TControl );
end;
并正在实施中:
constructor TFocusObserver.Create;
begin
l := TList.Create;
end;
destructor TFocusObserver.Destroy;
var i: integer;
begin
for i := 0 to l.Count - 1 do
TRegisteredComp(l[i]).Free;
l.Free;
inherited;
end;
procedure TFocusObserver.reg( c: TControl );
var
rc: TRegisteredComp;
begin
rc := TRegisteredComp.Create( c );
l.Add( rc );
end;
constructor TRegisteredComp.Create(c: TControl);
begin
fControl := c;
fowndproc := c.WindowProc;
c.WindowProc := HookWndProc;
end;
destructor TRegisteredComp.Destroy;
begin
fControl.WindowProc := fowndproc;
inherited;
end;
procedure TRegisteredComp.HookWndProc(var Message: TMessage);
begin
if ( Message.Msg = CM_FOCUSCHANGED ) and
( TControl(Message.LParam) = fControl ) then
form1.ListBox1.Items.Add( 'focused: ' + fControl.Name );
fowndproc( Message );
end;
不仅仅是注册您要观看的控件,例如:
procedure TForm1.FormCreate(Sender: TObject);
var
i: Integer;
begin
fo := TFocusObserver.Create;
for i := 0 to ControlCount - 1 do
fo.reg( Controls[i] );
end;
听起来怎么样?