在这篇文章中,我们将学习如何在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","ggarung@rediffmail.com",MessageBox.IconInformation);;
}
public static void Main(string[] args) {
Application.Run(new MenuTest());;
}
}
【注:本文由控件中国网转载】