Delphi - Catch all action.onexecute from an application
Asked Answered
D

2

6

I have a big application with hundreds of TActions. Each of them is used and implements different functionality needed.

It is possible to catch (hook) all the TAction.OnExecute from an application? Is there any windows message which I can hook so I can log the action name which was executed?

Danialah answered 21/12, 2011 at 10:8 Comment(0)
S
13

You just need to add a TApplicationEvents object and handle the OnActionExecute event. The event handler is passed the Action instance and so can readily obtain the name of the action.

The OnActionExecute event will fire before the action's OnExecute event fires. You can even stop the action's OnExecute event from firing by setting the Handled parameter to True in your OnActionExecute event handler.

Silurid answered 21/12, 2011 at 10:15 Comment(1)
Just an FYI, the TApplication.OnActionExecute event is the second hook that processes a TAction. If the TAction is associated with a TActionList, the TActionList.OnExecute event gets first dibs on the TAction. If that event handler returns True, the TApplication.OnActionExecute event is NOT triggered.Stadtholder
D
2

Based on David's answer I've made a small example:

program Project1;

uses
  ExceptionLog,
  Forms,
  Unit2 in 'Unit2.pas' {Form2},
  AppEvnts,
  Classes,
  Windows,
  SysUtils;

{$R *.res}

type TAppEventsHack = class
   procedure onAppEvtExec(Action:TBasicAction;var Handled:Boolean);
 end;

var aEvHack : TAppEventsHack;
    aAppEvents : TApplicationEvents;

{ TAppEventsHack }

procedure TAppEventsHack.onAppEvtExec(Action: TBasicAction;
  var Handled: Boolean);
begin
   OutputDebugString(PAnsiChar(Action.Name));
   Handled := False;
end;

begin
  Application.Initialize;
 try
  aEvHack := TAppEventsHack.Create;
  aAppEvents := TApplicationEvents.Create(nil);
  aAppEvents.OnActionExecute := aEvHack.onAppEvtExec;

  Application.CreateForm(TForm2, Form2);
  Application.Run;
 finally
  freeandnil(aEvHack);
  freeandnil(aAppEvents);
 end;
end.
Danialah answered 21/12, 2011 at 10:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.