tags:

views:

154

answers:

1
A: 

(deleted old - ugly answer completely)


It's pretty easy actually - once Remy tells what to do (see comments).

Here's the menu structure for the below sample

File1           Edit1
  FileItem11      EditItem11
  FileItem21      EditItem21

and two popup menu items. The code:  

type
  TForm1 = class(TForm)
    MainMenu1: TMainMenu;
    File1: TMenuItem;
    FileItem11: TMenuItem;
    FileItem21: TMenuItem;
    Edit1: TMenuItem;
    EditItem11: TMenuItem;
    EditItem21: TMenuItem;
    PopupMenu1: TPopupMenu;
    PopupItem11: TMenuItem;
    PopupItem21: TMenuItem;
    procedure PopupItem11Click(Sender: TObject);
    procedure PopupItem21Click(Sender: TObject);
  private
    FSelectedItem: TMenuItem;
    FTracking: Boolean;
    procedure MenuRButtonUp(var Msg: TMessage); message WM_MENURBUTTONUP;
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

{ TForm1 }

procedure TForm1.MenuRButtonUp(var Msg: TMessage);
var
  Cmd: UINT;
begin
  if not FTracking then
    FSelectedItem :=
        MainMenu1.FindItem(GetMenuItemID(Msg.LParam, Msg.WParam), fkCommand);

  if (not FTracking) and (FSelectedItem <> nil) then begin
    FTracking := True;
    LongBool(Cmd) := TrackPopupMenuEx(PopupMenu1.Handle,
                            TPM_RECURSE or TPM_BOTTOMALIGN or TPM_RETURNCMD,
                            Mouse.CursorPos.X, Mouse.CursorPos.Y, Handle, nil);
    FTracking := False;
    if Cmd <> 0 then
      PopupMenu1.DispatchCommand(Cmd);
  end;
  inherited;
end;

procedure TForm1.PopupItem11Click(Sender: TObject);
begin
  Caption := 'Popup Item 1 clicked on ' + FSelectedItem.Caption;
end;

procedure TForm1.PopupItem21Click(Sender: TObject);
begin
  // whatever..
  Caption := 'Popup Item 2 clicked on ' + FSelectedItem.Caption;
end;
Sertac Akyuz
-1, for saying that standard menus do not support richt-clicking. They do. This is possible via the `WM_MENURBUTTONUP` message, which was introduced for this exact purpose: http://msdn.microsoft.com/en-us/library/ms647610.aspx. Do a search through the archives at http://www.deja.com, there are plenty of examples of using `WM_MENURBUTTONUP` in Delphi.
Remy Lebeau - TeamB
@Remy - I had no problem detecting right-clicks, I didn't know about WM_MENURBUTTONUP but otherwise the code I posted responds to right-clicks. I guess my main problem was I also didn't know about `TPM_RECURSE`. *Thank you*, that's two key items I didn't know about!
Sertac Akyuz
great job , great code. thank you very much to everyone. p.s. @sertac bey, ilgi ve alakaniz icin size ayri tesekkur ederim :)
delphi2010
@delphi - Bisey değil, ben tesekkur ederim. :) BTW, you can [accept the answer](http://meta.stackoverflow.com/questions/5234/how-does-accepting-an-answer-work/5235#5235) if it solves your problem. ;)
Sertac Akyuz