
例如使用者按下 Button 後,在命令列印出 "button click" 的訊息,這時候就要設定 Button 的 Click 屬性,替 Click 增加一個 EventHandler 物件 (object) ,並且另外設計 button_Click() 方法進行印出訊息的工作
this.button1.Click += new EventHandler(this.button_Click);
button_Click() 如下
private void button_Click(object sender, EventArgs e) {
Console.WriteLine("button click");
}同樣的,使用者在 TextBox 輸入文字(按下按鍵),我們希望在命令列印出訊息,這裡需要在 TextBox 的 KeyPress 屬性新增 KeyPressEventHandler 物件
this.textbox1.KeyPress += new KeyPressEventHandler(this.textbox_KeyPress);
textbox_KeyPress() 如下
private void textbox_KeyPress(object sender, EventArgs e) {
Console.WriteLine("key press");
}ListBox 則是在命令列印出使用者選擇的選項,這跟 Button 一樣設定 Click 屬性即可
this.listbox1.Click += new EventHandler(this.listbox_Click);
listbox_Click() 如下
private void listbox_Click(object sender, EventArgs e) {
Console.WriteLine(this.listbox1.SelectedItem);
}ListBox 的 SelectedItem 屬性就是被選取選項的文字標籤。
完整的 guidemo.cs 修改如下
using System;
using System.Drawing;
using System.Windows.Forms;
public class Form1 : Form {
public Button button1;
public TextBox textbox1;
public ListBox listbox1;
public Form1() {
this.button1 = new Button();
this.button1.Location = new Point(10, 10);
this.button1.Text = "Click Me!!";
this.button1.Click += new EventHandler(this.button_Click);
this.textbox1 = new TextBox();
this.textbox1.Location = new Point(10, 45);
this.textbox1.Text = "Input Something.....";
this.textbox1.KeyPress += new KeyPressEventHandler(this.textbox_KeyPress);
this.listbox1 = new ListBox();
this.listbox1.Location = new Point(10, 80);
this.listbox1.Items.Add("Choice 1");
this.listbox1.Items.Add("Choice 2");
this.listbox1.Items.Add("Choice 3");
this.listbox1.Items.Add("Choice 4");
this.listbox1.Click += new EventHandler(this.listbox_Click);
this.Controls.Add(button1);
this.Controls.Add(textbox1);
this.Controls.Add(listbox1);
}
private void button_Click(object sender, EventArgs e) {
Console.WriteLine("button click");
}
private void textbox_KeyPress(object sender, EventArgs e) {
Console.WriteLine("key press");
}
private void listbox_Click(object sender, EventArgs e) {
Console.WriteLine(this.listbox1.SelectedItem);
}
[STAThread]
static void Main() {
Application.Run(new Form1());
}
}
/* 《程式語言教學誌》的範例程式
http://pydoing.blogspot.com/
檔名:guidemo.cs
功能:示範 C# 程式
作者:張凱慶
時間:西元 2012 年 10 月 */編譯執行,結果如下

好了, GUI 的基本概念大體如此,接下來我們要來實際建置 EncryptGUI 囉!
| 中英文術語對照 | |
|---|---|
| 程式 | program |
| 屬性 | property |
| 事件 | event |
| 方法 | method |
| 物件 | object |
您可以繼續參考
GUI 篇
相關目錄
回 C# 入門指南
回 C# 教材
回首頁
參考資料
http://msdn.microsoft.com/zh-tw/library/awbftdfh%28v=vs.80%29.aspx
http://msdn.microsoft.com/zh-tw/library/ms366768%28v=vs.80%29.aspx
http://msdn.microsoft.com/zh-tw/library/w369ty8x%28v=vs.80%29.aspx
沒有留言:
張貼留言