unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, Menus;

type
  TForm1 = class(TForm)
    procedure FormCreate(Sender: TObject);
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

//uses Menus; {我习惯在这里引用单元, 但 Menus 不行, 它会自动到 interface 区}

var
  MyMenu: TMainMenu; {声明菜单对象 MyMenu}
  Item: TMenuItem;   {虽然菜单项不止一个, 但可以只声明一个变量; 因为建立对象后, 上层会统一管理}

procedure TForm1.FormCreate(Sender: TObject);
begin
  MyMenu := TMainMenu.Create(Self); {属主参数定为 Self 就不用想着释放了}
  Self.Menu := MyMenu;              {让主窗口使用这个菜单}

  Item := TMenuItem.Create(MyMenu); {属主给 MyMenu 或 Self 都一样; 但如果 nil 就要想着手动释放}
  Item.Caption := 'AA';             {设定 Caption 是必要的, 不然会显示空菜单项}
  MyMenu.Items.Add(Item);

  Item := TMenuItem.Create(MyMenu); {上一个菜单已被 MyMenu 管理, 可以用 Item 创建其他对象}
  Item.Caption := 'BB';
  MyMenu.Items.Add(Item);

  Item := TMenuItem.Create(MyMenu);
  Item.Caption := 'CC';
  MyMenu.Items.Add(Item);
end;

end.

效果如下:


posted on 2008-02-04 11:18  万一  阅读(3042)  评论(5编辑  收藏  举报