Closing popup menu in system tray application

Question:

Sometimes, my popup menu in my tray application does not close when it loses focus. How can I get it to close?

Answer:

When processing the message to pop up the menu, you need to set the foreground window, then send a WM_NULL message after the menu popup.

procedure TForm1.WndProc(var Msg : TMessage);

var

  p : TPoint;

begin

  case Msg.Msg of

  WM_USER + 1:

  case Msg.lParam of

  WM_RBUTTONDOWN: begin

  SetForegroundWindow(Handle);

  GetCursorPos(p);

  PopupMenu1.Popup(p.x, p.y);

  PostMessage(Handle, WM_NULL, 0, 0);

  end;

  end;

  end;

  inherited;

end;