Message Hijacking via SetWindowLongPtr - Delphi

DarkCoderSc personal avatar
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.

Depends On


Created

April 24, 2025

Last Revised

May 14, 2025