用C#设计Windows应用程序模板(5)

[摘要]事件处理器在windows程序设计中添加事件处理器是最重要的任务。事件处理器保证了程序与用户交互,同时完成其他重要的功能。在c#中你可以给控件和菜单事件添加事件处理器以俘获你想处理的事件,下面的代码给Button控件的click事件设计了一个事件处理器:button.Click+=newSystem

事件处理器

在windows程序设计中添加事件处理器是最重要的任务。事件处理器保证了程序与用户交互,同时完成其他重要的功能。在c#中你可以给控件和菜单事件添加事件处理器以俘获你想处理的事件,下面的代码给Button控件的click事件设计了一个事件处理器:

button.Click += new System.EventHandler(this.button_Click);

button_Click事件处理器必须被处理:

private void button_Click(Object sender, System.EventArgs e) {

MessageBox.Show("Thank you.", "The Event Information");

}

MenuItem 对象在实例化的同时可以给赋以一个事件处理器:
fileNewMenuItem = new MenuItem("&New",

new System.EventHandler(this.fileNewMenuItem_Click), Shortcut.CtrlN);
fileOpenMenuItem = new MenuItem("&Open",

new System.EventHandler(this.fileOpenMenuItem_Click), Shortcut.CtrlO);
fileSaveMenuItem = new MenuItem("&Save",

new System.EventHandler(this.fileSaveMenuItem_Click), Shortcut.CtrlS);
fileSaveAsMenuItem = new MenuItem("Save &As",

new System.EventHandler(this.fileSaveAsMenuItem_Click));
fileMenuWithSubmenu = new MenuItem("&With Submenu");
submenuMenuItem = new MenuItem("Su&bmenu",

new System.EventHandler(this.submenuMenuItem_Click));
fileExitMenuItem = new MenuItem("E&xit",

new System.EventHandler(this.fileExitMenuItem_Click));

你不能给工具按钮指派一个事件处理器,但可以给工具条指派一个事件处理器:
toolBar.ButtonClick += new

ToolBarButtonClickEventHandler(this.toolBar_ButtonClick);

protected void toolBar_ButtonClick(Object sender, ToolBarButtonClickEventArgse) {
// Evaluate the Button property to determine which button was clicked.

switch (toolBar.Buttons.IndexOf(e.Button)) {

case 1:

MessageBox.Show("Second button.", "The Event Information");

break;

case 2:

MessageBox.Show("third button", "The Event Information");

break;

case 3:

MessageBox.Show("fourth button.", "The Event Information");

break;

}

}
例子中也给窗体的close事件设计了一个事件处理器,通过重载OnClosing方法你可以接收用户点击窗体的X按钮,这样你可以取消关闭事件:
protected override void OnClosing(CancelEventArgs e) {

MessageBox.Show("Exit now.", "The Event Information");

}
现在我们的模板就完成了,你可以使用他开始你的WINDOWS应用程序设计。




免责声明:

本站系本网编辑转载,会尽可能注明出处,但不排除无法注明来源的情况,转载目的在于传递更多信息,并不代表本网赞同其观点和对其真实性负责。如涉及作品内容、版权和其它问题,请在30日内与本网联系, 来信: liujun@soft6.com 我们将在收到邮件后第一时间删除内容!

[声明]本站文章版权归原作者所有,内容为作者个人观点,不代表本网站的观点和对其真实性负责,本站拥有对此声明的最终解释权。