在Delphi中挂接DLL函数 [英] Hooking a DLL function in Delphi
本文介绍了在Delphi中挂接DLL函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个coclass,它检查注册表以确定是否安装了应用程序,但它在这方面做得很差,没有找到应用程序的较新版本。如果安装了与之竞争的应用程序,它将尝试打开该应用程序。如果已经卸载了与之竞争的应用程序,程序将崩溃。这个coclass是在一个DLL文件中定义的,我没有这个库的源代码,所以我不能简单地更改它。我一直在研究使用挂钩将函数替换为有效的函数,但当我查看有关使用SetWindowsHookEx的MSDN文档时,它似乎很复杂。谁能举例说明如何使用SetWindowsHookEx或其他连接到Windows的方法?
谢谢
编辑:我想指出的是,我接受了我所做的答案,因为它对我有效。当问题被问到时,我不能使用另一个答案,但它看起来一样好。
推荐答案
以下是我自己的代码库中的一个简短示例,它展示了最基本的挂钩技术:
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.
这篇关于在Delphi中挂接DLL函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文