From: koterski@genghis (Steve Koterski)
Newsgroups: comp.lang.pascal
Subject: Re: Delphi: Setting procedures for dynamic menus
Date: 18 Apr 1995 15:36:50 GMT
Organization: Borland Intl

James Martin (martinj@cais.com) wrote:
: How do you assign a procedure to a menu item that you create
: dynamicaly?
: It's real easy with the object inspector, but how do you do
: that sort of thing for nonvisual objects?

First, the event procedure that will be associated with the newly created
menu item (TMenuItem) must already exist. Next, when the new menu item
is created (that is, when the Create method for TMenuItem is called), the
OnClick pointer property should be set to point to the target procedure.
This can actually be done at any time once the TMenuItem component has
been created. If the TMenuItem exists, you can freely set or reset the
OnClick property value to point to a procedure or nil (to have it point
to nothing). The example below establishes the OnClick event procedure for
three dynamically created TMenuItem components, using the same event
procedure for all three.

unit Unit1;

interface

uses
  SysUtils, WinTypes, WinProcs, Messages, Classes, Graphics, Controls,
  Forms, Dialogs, StdCtrls, Menus;

type
  TForm1 = class(TForm)
    MainMenu1: TMainMenu;
    File1: TMenuItem;
    Edit1: TEdit;
    procedure FormShow(Sender: TObject);
  private
    { Private declarations }
    procedure DooDah(Sender: TObject);
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.DFM}

procedure TForm1.FormShow(Sender: TObject);
var
  NewItem: TMenuItem;
  i: Integer;
begin
  for i := 1 to 3 do begin
    NewItem := TMenuItem.Create(Self);
    NewItem.Name := 'Item' + IntToStr(i);
    NewItem.Caption := 'Item' + IntToStr(i);
    NewItem.OnClick := DooDah;
    File1.Add(NewItem);
  end;
end;

procedure TForm1.DooDah(Sender: TObject);
begin
  Edit1.Text := (Sender as TMenuItem).Caption;
end;

end.

It is in the OnCreate event procedure for the TForm that the menu items
are created and the OnClick event procedure pointer property for each is
set. The For loop creates each new TMenuItem, sets the Name property,
sets the Caption property, and sets the OnClick property. As each is
created, the Add method is called to add the new menu item to the existing
TMenuItem (File1), forming a pull-down menu.

--
_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/
_/ Steve Koterski               _/   The opinions expressed here are    _/
_/ koterski@borland.com         _/         exclusively my own           _/
_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/
