2

我有一个 coclass 可以检查注册表以确定是否安装了应用程序,但它做得很差并且找不到更新版本的应用程序。如果安装了竞争应用程序,它将尝试打开该应用程序。如果竞争应用程序已被卸载,程序将崩溃。这个 coclass 是在一个 DLL 文件中定义的,我没有库的源代码,所以我不能改变它。我一直在研究使用挂钩来用一个有效的函数替换该函数,但是当我查看有关使用 SetWindowsHookEx 的 MSDN 文档时,它似乎很复杂。有人可以提供一个如何使用 SetWindowsHookEx 或其他连接 Windows 的方法的示例吗?

谢谢你

编辑:我想指出我接受了我所做的答案,因为它对我有用。在提出问题时我无法使用其他答案,但它看起来一样好。

4

3 回答 3

6

这是我自己的代码库中的一个简短示例,它显示了最基本的挂钩技术:

unit MethodHooker;

interface

implementation

uses
  SysUtils, Windows, Classes;

procedure Patch(Address: Pointer; const NewCode; Size: Integer);
var
  NumberOfBytes: DWORD;
begin
  WriteProcessMemory(GetCurrentProcess, Address, @NewCode, Size, NumberOfBytes);
end;

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

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

function GetCursorPos(var lpPoint: TPoint): BOOL; stdcall;
(* The GetCursorPos API in user32 fails if it is passed a memory address >2GB which
   breaks LARGEADDRESSAWARE apps.  We counter this by calling GetCursorInfo instead
   which does not suffer from the same problem. *)
var
  CursorInfo: TCursorInfo;
begin
  CursorInfo.cbSize := SizeOf(CursorInfo);
  Result := GetCursorInfo(CursorInfo);
  if Result then begin
    lpPoint := CursorInfo.ptScreenPos;
  end else begin
    lpPoint := Point(0, 0);
  end;
end;

initialization
  if not ModuleIsPackage then begin
    if not CheckWin32Version(6, 1) then begin
      //this bug was fixed in Windows 7
      Redirect(@Windows.GetCursorPos, @MethodHooker.GetCursorPos);
    end;

end.
于 2011-03-17T19:06:55.340 回答
5

对于一个非常好的绕行/挂钩单元(可以检查跳跃并应用新的偏移量!)我会推荐KOLdetours.pas

我在许多项目中使用它,例如我的 AsmProfiler。

顺便说一句:绕道你会得到一个“蹦床”,所以你也可以调用原始函数!

于 2011-03-17T19:16:33.363 回答
4

我是 koldetours 的作者。许可证对所有人免费:即,即使在商业程序中也可以随意使用。基本上它是真正的开源,不受任何许可的限制。就像派生它的代码一样。它在标题中明确说明了这一点。

于 2012-01-18T11:23:23.943 回答