在 Form1 上拖一个 TreeView 控件,然后参考一下代码:
unit Unit1; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Menus, ComCtrls; type TForm1 = class(TForm) TreeView1: TTreeView; function CreateMenu(pCation: string): TPopupMenu; procedure FormCreate(Sender: TObject); procedure TreeView1MouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); private { Private declarations } public { Public declarations } end; var Form1: TForm1; implementation {$R *.DFM} function TForm1.CreateMenu(pCation: string): TPopupMenu; var pPopupMenu:TPopupMenu; pMenu:TMenuItem; i:integer; begin pPopupMenu:=TPopupMenu.Create(self); for i:=0 to 5 do begin pMenu :=TMenuItem.Create(pPopupMenu); pMenu.Caption :=pCation+inttostr(i); pPopupMenu.Items.Add(pMenu); end; result:=pPopupMenu; end; procedure TForm1.FormCreate(Sender: TObject); begin TreeView1.Items.AddObject(nil,’test’,Pointer(CreateMenu(’test’))); TreeView1.Items.AddObject(nil,’xxx’,Pointer(CreateMenu(’xxx’))); TreeView1.Items.AddObject(nil,’ddd’,Pointer(CreateMenu(’ddd’))); TreeView1.Items.AddObject(nil,’ccc’,Pointer(CreateMenu(’ccc’))); end; procedure TForm1.TreeView1MouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); var pNode: TTreeNode; begin if button=mbright then begin pNode :=TreeView1.GetNodeAt(x,y); if (pNode〈〉nil) then TreeView1.PopupMenu :=TPopupMenu(pNode.data); end end; end.