Mega Code Archive

 
Categories / Delphi / VCL
 

Creating menuitems on the fly

Title: Creating menuitems on the fly Question: How to create a menuitem at runtime Answer: Sample program 1. Add a TMainMenu to your form (this tip also works with TPopUpMenu or any other descendant of TMenu) 2. Add a TButton to the form and create an event handler for the OnClick event. 3. Paste the following code: procedure TForm1.Button1Click(Sender: TObject); var item: TMenuItem; item2: TMenuItem; begin item := TMenuItem.Create(MainMenu1); item.Caption := '&File'; MainMenu1.Items.Add(item); item2 := TMenuItem.Create(MainMenu1); item2.Caption := 'E&xit'; item2.OnClick := ExitClick; item.Add(item2); end; 4. Add a new event handler routine to your form. This event handler will be called by the menu item we just added. To add the new event handler, add the following code to your form unit: procedure TForm1.ExitClick(Sender: TObject); begin Application.Terminate; end; and invoke the code completion feature (Delphi 4 and up) by pressing CTRL+SHIFT+C. Your code should now look like this: unit Unit1; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Menus; type TForm1 = class(TForm) MainMenu1: TMainMenu; Button1: TButton; procedure Button1Click(Sender: TObject); procedure ExitClick(Sender: TObject); private { Private declarations } public { Public declarations } end; var Form1: TForm1; implementation {$R *.DFM} procedure TForm1.Button1Click(Sender: TObject); var item: TMenuItem; item2: TMenuItem; begin item := TMenuItem.Create(MainMenu1); item.Caption := '&File'; MainMenu1.Items.Add(item); item2 := TMenuItem.Create(MainMenu1); item2.Caption := 'E&xit'; item2.OnClick := ExitClick; item.Add(item2); end; procedure TForm1.ExitClick(Sender: TObject); begin Application.Terminate; end; end. How does it work? All TMenu descendants are built like a tree. You have the root, which is the TMainMenu or TPopUpMenu component. This component contains the top-level menu items, which in turn can contain sub menu items. So, in order to add a menu item to an existing menu, you need to have a reference on the menu item you want to add to. By invoking TMenuItem.Create(), you create a new menu item and make it a child of the menu component. Next, you add this new item to the item you want to become the parent of the new item. That's all. Pretty easy, isn't it?