Message Hijacking via SetWindowLongPtr - Delphi
Description
This snippet demonstrates how to intercept the WM_CLOSE
message and prompt the user to confirm whether they really want to close the active (target) window. Note that for this to work, SetWindowLongPtr
must be called from within the same process as the target window. One technique used often by malware authors is to inject a DLL into the target process in order to intercept and interact with remote windows using this technique..

DarkCoderSc
Jean-Pierre LESUEUR
function HijackedWndProc(hWnd : THandle; msg: UINT; wParam : WPARAM; lParam: LPARAM) : LRESULT; stdcall;
begin
case msg of
WM_CLOSE : begin
if MessageBox(hWnd, 'You really wan''t to close this window?', 'O_o', MB_ICONQUESTION + MB_YESNO) = ID_NO then
Exit(); // Default Window Handler not called so nothing happens
end;
// ... Intercept and handle other messages ... //
end;
// Default action triggered for received message
result := DefWindowProc(hWnd, msg, wParam, lParam);
end;
// ...
var ATargetWindow := GetActiveWindow();
var AOldWindowProc := SetWindowLongPtr(ATargetWindow, GWLP_WNDPROC, LONG_PTR(@HijackedWndProc));
if AOldWindowProc = 0 then
raise EWindowsException.Create('SetWindowLongPtr');
// Force `WM_CLOSE` to occure now (Debug)
SendMessage(ATargetWindow, WM_CLOSE, 0, 0);
// ...
// Restore original window handler when interception no longer needed
if SetWindowLongPtr(ATargetWindow, GWLP_WNDPROC, AOldWindowProc) = 0 then
raise EWindowsException.Create('SetWindowLongPtr');
Creating and researching code snippets takes time and effort. You’re welcome to share them through your own platforms, but please don’t forget to credit the original author, here: Jean-Pierre LESUEUR.
Implemented By Technique
Featured Windows APIs
Created
April 24, 2025
Last Revised
April 24, 2025