
我們得替每個視窗元件設定 Location 屬性 (property) ,這樣才能把視窗元件放到適合的位置。例如, guidemo.cs 中原有 Button 、 TextBox 、 ListBox 三個元件,我們把 Button 設定在座標 (10, 10) , TextBox 設定在座標 (10, 45) ,而 ListBox 設定在座標 (10, 80)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 | 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 .textbox1 = new TextBox(); this .textbox1.Location = new Point(10, 45); this .textbox1.Text = "Input Something....." ; 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 .Controls.Add(button1); this .Controls.Add(textbox1); this .Controls.Add(listbox1); } [STAThread] static void Main() { Application.Run( new Form1()); } } /* 《程式語言教學誌》的範例程式 檔名:guidemo.cs 功能:示範 C# 程式 作者:張凱慶 時間:西元 2012 年 10 月 */ |
Location 屬性需要用 Point 型態 (type) 的物件 (object) , Point 類別 (class) 放在 System.Drawing 裡面,因此要先 using 進來
1 | using System.Drawing; |
建立 Button 後,就設定 Location 屬性,需要先建立 Point 的物件,並把座標值當參數 (parameter) ,最後我們連帶設定 Button 的按鈕文字,也就是設定 Text 屬性
11 12 13 | this .button1 = new Button(); this .button1.Location = new Point(10, 10); this .button1.Text = "Click Me!!" ; |
TextBox 亦同,另外我們也設定文字方塊中的預設文字
15 16 17 | this .textbox1 = new TextBox(); this .textbox1.Location = new Point(10, 45); this .textbox1.Text = "Input Something....." ; |
ListBox 中,我們另外加入四個選項,這是用 Items 屬性呼叫 Add() 方法 (method)
19 20 21 22 23 24 | 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" ); |
編譯執行,結果如下

嗯,看起來是不是整齊、美觀多了,可是除了文字方塊可以輸入文字外,按鈕、選項都沒反應,這是因為我們還沒設定相關事件 (event) 處理唷!
中英文術語對照 | |
---|---|
屬性 | property |
型態 | type |
物件 | object |
類別 | class |
參數 | parameter |
方法 | method |
事件 | event |
您可以繼續參考
GUI 篇
相關目錄
回 C# 入門指南
回 C# 教材
回首頁
參考資料
http://msdn.microsoft.com/zh-tw/library/ms229601.aspx
http://msdn.microsoft.com/zh-tw/library/ettb6e2a.aspx
http://msdn.microsoft.com/zh-tw/library/ty26a068.aspx
http://msdn.microsoft.com/zh-tw/library/tkzw7bw7.aspx
2 則留言:
請問範例是針對windows嗎?mac下無法compile這個sample
terminal會顯示
error CS8027: Couldn't run pkg-config: ApplicationName='pkg-config', CommandLine='--libs dotnet', CurrentDirectory=''
用Mono提供的Xamarin Studio這個IDE也不行
這是在 Mac 編譯的唷,不過系統如果經過變動,例如安裝 mono 後又安裝其他軟體,就容易出現 error CS8027 的問題,疑似是 mono 的 bug ,建議完全移除 mono 後重新安裝,然後編譯看看,如果問題還是一樣,暫時換 MS-Windows 練習也許會比較 ok 唷! ^_^
張貼留言