C#Windows應(yīng)用程序開發(fā)之事件處理器
C#Windows應(yīng)用程序開發(fā)之事件處理器的前言:通常windows應(yīng)用程序都有相似的特征:控件、菜單、工具條、狀態(tài)欄等等。每次我們開始作一個新的windows應(yīng)用程序時都是以相同的事情開始:建立項(xiàng)目,添加控件和事件處理器。如果我們有一個模板,那么我們就可以節(jié)約大量的時間了。
在介紹如何建立模板的過程中,將涉及大量的微軟.net framework類庫的基本知識。如果你沒有使用集成開發(fā)環(huán)境那么本文介紹的模板對你將非常有用,如果你使用了visual studio.net這樣的集成開發(fā)環(huán)境你也可以從中了解控件的工作方式,這對你也是很有用的。
C#Windows應(yīng)用程序開發(fā)之事件處理器
在windows程序設(shè)計中添加事件處理器是最重要的任務(wù)。事件處理器保證了程序與用戶交互,同時完成其他重要的功能。在c#中你可以給控件和菜單事件添加事件處理器以俘獲你想處理的事件,下面的代碼給Button控件的click事件設(shè)計了一個事件處理器:
- button.Click += new System.EventHandler(this.button_Click);
C#Windows應(yīng)用程序開發(fā)之事件處理器之button_Click事件處理器必須被處理:
- private void button_Click(Object sender, System.EventArgs e) {
- MessageBox.Show("Thank you.", "The Event Information");
- }
C#Windows應(yīng)用程序開發(fā)之事件處理器之MenuItem 對象在實(shí)例化的同時可以給賦以一個事件處理器:
- 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));
C#Windows應(yīng)用程序開發(fā)之事件處理器遇到的問題:你不能給工具按鈕指派一個事件處理器,但可以給工具條指派一個事件處理器:
- toolBar.ButtonClick += new
- ToolBarButtonClickEventHandler(this.toolBar_ButtonClick);
- protected void toolBar_ButtonClick(Object sender, ToolBarButtonClickEventArgs
- e) {
- // 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;
- }
- }
C#Windows應(yīng)用程序開發(fā)之事件處理器的理解:例子中也給窗體的close事件設(shè)計了一個事件處理器,通過重載OnClosing方法你可以接收用戶點(diǎn)擊窗體的X按鈕,這樣你可以取消關(guān)閉事件:
- protected override void OnClosing(CancelEventArgs e) {
- MessageBox.Show("Exit now.", "The Event Information");
- }
C#Windows應(yīng)用程序開發(fā)之事件處理器的基本情況就向你介紹到這里,希望對你學(xué)習(xí)和理解C#Windows應(yīng)用程序開發(fā)之事件處理器有所幫助。
【編輯推薦】