我想在一个DLL文件中实现一个在系统关机、重启、注销前保存数据的功能,想用GetMessage钩子来得到,于是写了以下代码,可是一点用也没有,请问这是为什么MsgHook:=SetWindowsHookEx(WH_GETMESSAGE,@MsgProc,0,GetCurrentThreadId);function MsgProc(ncode,wparam,lparam:Integer):LRESULT;stdcall;
var
  mess:Cardinal;
begin
  mess:=pmsg(lparam)^.message;
  if (mess=WM_QUERYENDSESSION) or (mess=WM_ENDSESSION) or (mess=ENDSESSION_LOGOFF)then
  begin
    SaveInfo;
  end;
  Result:=CallNextHookEx(msgHook,ncode,wparam,lparam);
end;

解决方案 »

  1.   


    unit msghook;interfaceuses
      windows,
      messages,
      dialogs;var
      h: THandle;
      m: PMSG;  procedure EnableHook; export;
      procedure DisableHook; export;
      function GetMsgProc(code: integer; wParam: WPARAM; lParam: LPARAM): LRESULT; stdcall;implementationprocedure EnableHook; export;
    begin
      h:= SetWindowsHookEx(WH_GETMESSAGE,@GetMsgProc,Hinstance,0);
    end;procedure DisableHook; export;
    begin
      UnhookWindowsHookEx(h);
    end;function GetMsgProc(code: integer; wParam: WPARAM; lParam: LPARAM): LRESULT; stdcall;
    begin
      result:= 0;
      if code < 0 then
      begin
        result:= CallNextHookEx(h,code,wParam,lParam);
        exit;
      end
      else
      begin
        if code = HC_ACTION then
        begin
          m:= PMSG(lParam);
          if m^.message = WM_QUERYENDSESSION then showmessage('abort shutdown');
        end;
      end;
    end;end.library hook;{ Important note about DLL memory management: ShareMem must be the
      first unit in your library's USES clause AND your project's (select
      Project-View Source) USES clause if your DLL exports any procedures or
      functions that pass strings as parameters or function results. This
      applies to all strings passed to and from your DLL--even those that
      are nested in records and classes. ShareMem is the interface unit to
      the BORLNDMM.DLL shared memory manager, which must be deployed along
      with your DLL. To avoid using BORLNDMM.DLL, pass string information
      using PChar or ShortString parameters. }uses
      SysUtils,
      Classes,
      msghook in 'msghook.pas';{$R *.res}exports
      EnableHook,
      DisableHook;begin
      h:= 0;
    end.
    ---------------------------------------------------------------测试的工程如下:
    unit Unit1;interfaceuses
      Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
      Dialogs;type
      TForm1 = class(TForm)
        procedure FormCreate(Sender: TObject);
        procedure FormDestroy(Sender: TObject);
      private
        { Private declarations }
      public
        { Public declarations }
      end;    procedure EnableHook; external 'hook.dll' name 'EnableHook';
        procedure DisableHook; external 'hook.dll' name 'DisableHook';var
      Form1: TForm1;implementation{$R *.dfm}procedure TForm1.FormCreate(Sender: TObject);
    begin
      EnableHook;
    end;procedure TForm1.FormDestroy(Sender: TObject);
    begin
      DisableHook;
    end;end.