Subclassing / hooking windows with delphi

Sometimes it is necessary to hook windows messages for a particular window. This is also Referred as Sub classing a window .
I wrote a simple unit that does exactly that.
Please be aware, hooking window messages can go terrible wrong if you do not exactly know what your are doing. So be warned.
You can download this unit below.

And here is how to hook windows messages for a particular window using maxWndSubClassing

First of all, include the unit in your uses statement.

uses maxWndSubClassing;

I will demonstrate how to hook your own TForm, but obviously, doing it on your own form would be overkill and not useful in most scenarios. But hey, that is only a showcase.
In most real world scenarios you would do this for a window handle, that you did not created yourself.

type
  TForm1 = class(TForm)
    procedure FormCreate(Sender: TObject);
  private
    fWindowHook: TWndSubClass;
    procedure myWindowProc(var Msg: Messages.TMessage; var PrevendDefaultHandler: boolean);
  end;

Here is how the FormCreate procedure looks like

procedure TForm1.FormCreate(Sender: TObject);
begin
  // first create your TWndSubClass instance. TWndSubClass inherits from TComponent,therefore it will be destroyed automatically when its owner is destroyed.
  fWindowHook := TWndSubClass.Create(self);
  // assign an event, this will be the new window proc for that window.
  fWindowHook.OnMessage := MyMessageProc;
  // this line assigns the window handle that will be hooked.
  fWindowHook.HookedWnd := self.Handle;
end;

that is all you need to do. Your window message hook is set up and ready to go.

You now need to fill your event with some code.

procedure TForm1.myWindowProc(var Msg: Messages.TMessage; var PrevendDefaultHandler: boolean);
begin
// your code goes here
end;

obviously you want to react on some messages.
You can prevent the underlying message handlers to be called by setting PrevendDefaultHandler to True. But be aware, that may cause havoc, so do it only if you know what you are doing.

pas

MaxWndSubClassing

maxWndSubClassing.pas

2.0

4.5 KiB

203

Details

Download File

This entry was posted by on 26th May,2014, and is filed under Delphi. Follow any responses to this post through RSS 2.0 Both comments and pings are currently closed.