如何在代码中动态添加按钮控件

类别:.NET开发 点击:0 评论:0 推荐:

在这篇文章中,我们将学习如何在winform中添加按钮。我们可以在设计视图里添加按钮控件,也可以在代码中动态添加按钮控件,下面的代码显示了如何在winform中动态添加一个按钮控件。

using System;
using System.ComponentModel;
using System.WinForms;
using System.Drawing;

public class MenuTest :Form {
private MainMenu mainMenu;
private ContextMenu popUpMenu;
public MenuTest()  {
mainMenu = new MainMenu();
popUpMenu =new ContextMenu();
popUpMenu.MenuItems.Add("Hello",new EventHandler(pop_Clicked));
this.ContextMenu = popUpMenu;
MenuItem File = mainMenu.MenuItems.Add("&File");
File .MenuItems.Add(new MenuItem("&New",new EventHandler(this.FileNew_clicked),Shortcut.CtrlN));
File .MenuItems.Add(new MenuItem("&Open",new EventHandler(this.FileOpen_clicked),Shortcut.CtrlO));
File .MenuItems.Add(new MenuItem("&Exit",new EventHandler(this.FileExit_clicked),Shortcut.CtrlX));
this.Menu=mainMenu;
MenuItem About = mainMenu.MenuItems.Add("&About");
About.MenuItems.Add(new MenuItem("&About",new EventHandler(this.About_clicked),Shortcut.CtrlA));
this.Menu=mainMenu;
mainMenu.GetForm().BackColor = Color.Indigo ;

}
private void FileExit_clicked(object sender, EventArgs e) {
             this.Close();
                       }
private void FileNew_clicked(object sender, EventArgs e) {
             MessageBox.Show("New","MENU_CREATION",MessageBox.IconInformation);
                       }
private void FileOpen_clicked(object sender, EventArgs e) {
             MessageBox.Show("Open","MENU_CREATION",MessageBox.IconInformation);
                       }
private void pop_Clicked(object sender, EventArgs e) {
             MessageBox.Show("Popupmenu","MENU_CREATION",MessageBox.IconInformation);
                       }
private void About_clicked(object sender, EventArgs e) {
                MessageBox.Show("G.GNANA ARUN GANESH","
[email protected]",MessageBox.IconInformation);
                       }
public static void Main(string[] args) {
  Application.Run(new MenuTest());
   }  
}

本文地址:http://com.8s8s.com/it/it45710.htm