How to pass a method as callback to a Windows API call?

前端 未结 6 1860
萌比男神i
萌比男神i 2020-12-14 13:10

I\'d like to pass a method of a class as callback to a WinAPI function. Is this possible and if yes, how?

Example case for setting a timer:

TMyClass          


        
6条回答
  •  猫巷女王i
    2020-12-14 13:46

    The TimerProc procedure should be a standard procedure, not a method pointer.

    A method pointer is really a pair of pointers; the first stores the address of a method, and the second stores a reference to the object the method belongs to

    Edit

    This might be as much OOP as you are going to get it. All the nasty stuff is hidden from anyone using your TMyClass.

    unit Unit2;
    
    interface
    
    type
      TMyClass = class
      private
        FTimerID: Integer;
        FPrivateValue: Boolean;
      public
        constructor Create;
        destructor Destroy; override;
        procedure DoIt;
      end;
    
    implementation
    
    uses
      Windows, Classes;
    
    var
      ClassList: TList;
    
    constructor TMyClass.Create;
    begin
      inherited Create;
      ClassList.Add(Self);
    end;
    
    destructor TMyClass.Destroy;
    var
      I: Integer;
    begin
      I := ClassList.IndexOf(Self);
      if I <> -1 then
        ClassList.Delete(I);
      inherited;
    end;
    
    procedure TimerProc(Wnd:HWND; uMsg:DWORD; idEvent:PDWORD; dwTime:DWORD); stdcall;
    var
      I: Integer;
      myClass: TMyClass;
    begin
      for I := 0 to Pred(ClassList.Count) do
      begin
        myClass := TMyClass(ClassList[I]);
        if myClass.FTimerID = Integer(idEvent) then
          myClass.FPrivateValue := True;
      end;
    end;
    
    procedure TMyClass.DoIt;
    begin
      FTimerID := SetTimer(0, 0, 8, @TimerProc);  // <-???- that's what I want to do (last param)
    end;
    
    initialization
      ClassList := TList.Create;
    
    finalization
      ClassList.Free;
    
    end.
    

    Edit: (as mentioned by glob)

    Don't forget to add the stdcall calling convention.

提交回复
热议问题