Search code examples
delphidelphi-2009popupmenutrayicon

Why the famous workaround for closing a popup menu with Esc is not working with a private handle?


I made a component to use tray icons in my application and when the icon shows the popup menu, it can't be closed with Esc key. Then I found a workaround here, by David Heffernan. I integrate the code in my component and now the menu can be closed with Esc but after I popup the menu my application become compleately dead, I can't access anything on the main form, even the system buttons doesn't work any more.

Here is the code to reproduce the problem:

unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, Menus, ShellApi;

const WM_ICONTRAY = WM_USER+1;

type
  TForm1 = class(TForm)
    PopupMenu1: TPopupMenu;
    Test1: TMenuItem;
    Test2: TMenuItem;
    procedure FormCreate(Sender: TObject);
    procedure FormDestroy(Sender: TObject);
  private
    IconData: TNotifyIconData;
  protected
    procedure PrivateWndProc(var Msg: TMessage); virtual;
  public
    PrivateHandle:HWND;
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

procedure TForm1.FormCreate(Sender: TObject);
begin
 PrivateHandle:=AllocateHWnd(PrivateWndProc);

 // add an icon to tray
 IconData.cbSize:=SizeOf(IconData);
 IconData.Wnd:=PrivateHandle;
 IconData.uID:=1;
 IconData.uFlags:=NIF_MESSAGE + NIF_ICON;
 IconData.uCallbackMessage:=WM_ICONTRAY;
 IconData.hIcon:=Application.Icon.Handle;
 Shell_NotifyIcon(NIM_ADD, @IconData);
end;

procedure TForm1.FormDestroy(Sender: TObject);
begin
 IconData.uFlags:=0;
 Shell_NotifyIcon(NIM_DELETE, @IconData);
 DeallocateHWnd(PrivateHandle);
end;

procedure TForm1.PrivateWndProc(var Msg: TMessage);
var p:TPoint;
begin
 if (Msg.Msg = WM_ICONTRAY) and (Msg.LParam=WM_RBUTTONUP) then
  begin
   GetCursorPos(p);
   SetForegroundWindow(PrivateHandle);
   PopupMenu1.Popup(p.x,p.y);
   PostMessage(PrivateHandle, WM_NULL, 0, 0);
  end;
end;

end.

Solution

  • I guess you just missed to call DefWindowProc. Try this:

    procedure TForm1.PrivateWndProc(var Msg: TMessage);
    begin
      if (Msg.Msg = WM_ICONTRAY) and (Msg.lParam = WM_RBUTTONUP) then
      begin
        ...
      end
      else
        Msg.Result := DefWindowProc(PrivateHandle, Msg.Msg, Msg.wParam, Msg.lParam);
    end;