using System ; using System.Windows.Forms ; using System.Drawing ; using System.ComponentModel ; class RuntimeMenus : Form { private MainMenu myMenu ; private MenuItem mnuFile , mnuExit , mnuRtime ; private Button btnAdd , btnRemove , btnClose ; static int i ; public RuntimeMenus ( ) { InitializeComponents ( ) ; }
public void InitializeComponents ( ) { //初始化 Main Menus myMenu = new MainMenu ( ) ; mnuFile = new MenuItem ( "文件" ) ; mnuRtime = new MenuItem ( "运行菜单项目" ) ;
//往 Main Menu里面加入菜单 myMenu.MenuItems.Add ( mnuFile ) ; myMenu.MenuItems.Add ( mnuRtime ) ;
//初始化 Exit 菜单项,设定了事件和快捷键 mnuExit = new MenuItem ( "退出" , new EventHandler ( btnClose_Click ) , Shortcut.CtrlX ) ; //把菜单项加入到文件File菜单中 mnuFile.MenuItems.Add ( mnuExit ) ;//初始化添加按钮 btnAdd = new Button ( ) ; btnAdd.Location = new Point ( 275 , 20 ) ; btnAdd.Text = "添加菜单" ; btnAdd.Click += new EventHandler ( btnAdd_Click ) ; btnAdd.Size = new Size ( 100 , 30 ) ; //初始化删除按钮 btnRemove = new Button ( ) ; btnRemove.Location = new Point ( 275 , 60 ) ; btnRemove.Text = "删除菜单" ; btnRemove.Click += new EventHandler ( btnRemove_Click ) ; btnRemove.Size = new Size ( 100 , 30 ) ; //初始化关闭按钮 btnClose = new Button ( ) ; btnClose.Location = new Point ( 275 , 100 ) ; btnClose.Text = "退出" ; btnClose.Click += new EventHandler ( btnClose_Click ) ; btnClose.Size = new Size ( 100 , 30 ) ;
//在窗体中加入按钮 this.Controls.Add ( btnAdd ) ; this.Controls.Add ( btnRemove ) ; this.Controls.Add ( btnClose ) ; //设置窗体的属性 this.MaximizeBox = false ; this.MinimizeBox = false ; this.Text = "动态处理菜单程序窗口!" ; // 设定本窗体的MainMenu this.Menu = myMenu ; this.Size = new Size ( 400 , 250 ) ; this.CancelButton = btnClose ; this.StartPosition = FormStartPosition.CenterScreen ;
} //以下是动态加入菜单项 protected void btnAdd_Click ( object sender , EventArgs e ) { mnuRtime.MenuItems.Add ( "运行菜单 " + ( i + 1 ) , new EventHandler ( mnuRtime_Click ) ) ; i++ ; }
//以下是动态删除菜单项 protected void btnRemove_Click ( object sender , EventArgs e ) { mnuRtime.MenuItems.RemoveAt ( i - 1 ) ; i = i - 1 ; } protected void mnuRtime_Click ( object sender , EventArgs e ) { String s = sender.ToString ( ) ; MessageBox.Show ( "你选择的是 " + s.Substring ( 28 ) , "菜单选择窗口!" , MessageBoxButtons.OK , MessageBoxIcon.Information ) ; } //退出应用程序 protected void btnClose_Click ( object sender , EventArgs e ) { Application.Exit ( ) ; } public static void Main ( ) { Application.Run ( new RuntimeMenus ( ) ) ; } } |