如何知道表单是否已创建?

use*_*856 2 delphi runtime lazarus oncreate

我想找到一种方法来知道表单是在运行时创建的(或销毁的).这适用于Delphi或fpc.非常感谢

PS:有没有办法检索所有对象的信息?

Dav*_*nan 6

我希望有一个事件告诉我一个新对象刚刚在运行时创建(或销毁).

每当创建或销毁对象时,都不会触发内置事件.

因为我喜欢编写代码钩子,所以我提供以下单元.这会挂钩单元中的_AfterConstruction方法System.理想情况下它应该使用蹦床但我从未学会如何实施这些.如果您使用了真正的挂钩库,那么您可以做得更好.无论如何,这里是:

unit AfterConstructionEvent;

interface

var
  OnAfterConstruction: procedure(Instance: TObject);

implementation

uses
  Windows;

procedure PatchCode(Address: Pointer; const NewCode; Size: Integer);
var
  OldProtect: DWORD;
begin
  if VirtualProtect(Address, Size, PAGE_EXECUTE_READWRITE, OldProtect) then
  begin
    Move(NewCode, Address^, Size);
    FlushInstructionCache(GetCurrentProcess, Address, Size);
    VirtualProtect(Address, Size, OldProtect, @OldProtect);
  end;
end;

type
  PInstruction = ^TInstruction;
  TInstruction = packed record
    Opcode: Byte;
    Offset: Integer;
  end;

procedure RedirectProcedure(OldAddress, NewAddress: Pointer);
var
  NewCode: TInstruction;
begin
  NewCode.Opcode := $E9;//jump relative
  NewCode.Offset := NativeInt(NewAddress)-NativeInt(OldAddress)-SizeOf(NewCode);
  PatchCode(OldAddress, NewCode, SizeOf(NewCode));
end;

function System_AfterConstruction: Pointer;
asm
  MOV     EAX, offset System.@AfterConstruction
end;

function System_BeforeDestruction: Pointer;
asm
  MOV     EAX, offset System.@BeforeDestruction
end;

var
  _BeforeDestruction: procedure(const Instance: TObject; OuterMost: ShortInt);

function _AfterConstruction(const Instance: TObject): TObject;
begin
  try
    Instance.AfterConstruction;
    Result := Instance;
    if Assigned(OnAfterConstruction) then
      OnAfterConstruction(Instance);
  except
    _BeforeDestruction(Instance, 1);
    raise;
  end;
end;

initialization
  @_BeforeDestruction := System_BeforeDestruction;
  RedirectProcedure(System_AfterConstruction, @_AfterConstruction);

end.
Run Code Online (Sandbox Code Playgroud)

为处理程序分配处理程序,OnAfterConstruction只要创建对象,就会调用该处理程序.

我将它作为练习留给读者添加一个OnBeforeDestruction事件处理程序.

请注意,我并不是说这样的方法是一件好事.我只是回答你提出的直接问题.您可以自己决定是否要使用它.我知道我不会这样做!

  • +1但在我看来,在大多数情况下,他可以简单地继承一个共同的祖先形式.它将更简单,更易于管理 (3认同)