Search code examples
delphivcldelphi-11-alexandria

OnReceiveLocalNotification works well initially, but is not fired once the notification goes into Windows Action Center


In have made a VCL application with Delphi 11.3.

The OnReceiveLocalNotification event of TNotificationCenter works well (fires) if the user clicks my notification while it's initially visible (has popped up) in the lower right corner of the screen. But if the user does not react quickly and the notification goes into the Windows Action Center (like notifications do after a while), then, when the user clicks the notification there, the event is not fired. At least this is what happens on my Windows 11 PC.

Is this expected behaviour, or is something wrong here, and if so, what?

I would want to get notified when the user clicks the notification (as long as my application is still running), regardless of where the notification currently is being presented.

Code to reproduce the problem:

unit MainUnit;

interface

uses
  Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
  Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, System.Notification;

type
  TForm1 = class(TForm)
    Button1: TButton;
    procedure Button1Click(Sender: TObject);
    procedure ReceiveLocalNotification(Sender: TObject;
      ANotification: TNotification);
    procedure FormCreate(Sender: TObject);
  private
    { Private declarations }
    NotificationCenter1: TNotificationCenter;
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

procedure TForm1.Button1Click(Sender: TObject);
var
  N: TNotification;
begin
  N := NotificationCenter1.CreateNotification;
  try
    N.Title := 'My Title';
    N.AlertBody := 'My alert body';
    NotificationCenter1.PresentNotification(N);
  finally
    N.Free;
  end;
end;

procedure TForm1.FormCreate(Sender: TObject);
begin
  NotificationCenter1 := TNotificationCenter.Create(Self);
  NotificationCenter1.OnReceiveLocalNotification := ReceiveLocalNotification;
end;

procedure TForm1.ReceiveLocalNotification(Sender: TObject;
  ANotification: TNotification);
begin
  ShowMessage('I received the notification clicked event');
end;

end.

Solution

  • as specified Using Notifications

    Clicking the notifications in macOS, iOS, or Android, brings the application that sent the notification to the front, whether this application is running in the background or closed completely.

    There is no particular behaviour when the user clicks the notification in Windows.

    After the notification disappears,ONLY Windows no longer sends notification messages to the application that generated the notification.