C#編程三步走之二
2024-07-21 02:17:40
供稿:網友
將表單初始化成給定的規格涉及到對 tempconverter 對象的某些屬
性進行設置。有些屬性有改變值的方法,而其它屬性則要通過更新適
當的實例變量來直接修改。下面是有關代碼。如果想要得到關于
winforms
類的屬性和方法的更多信息,那么 .net framework sdk 所提供的文
檔可以算是一個很好的參考資料。
this.setsize(180,90);
this.borderstyle = formborderstyle.fixeddialog;
this.text = " +c -> +f / +f -> +c ";
this.startposition =
formstartposition.centerscreen;
this.helpbutton = false;
this.maximizebox = false;
現在把這些代碼放在一起進行編譯和運行,看看表單運行后是什么樣
子。這里要使用類定義,創建一個構造器(其中要包含以上的代碼來
初始化主窗口的外觀),并且要創建一個主方法來創建類的一個例
示。以下是完成這一工作的代碼:
public class tempconverter : system.winforms.form
{
public tempconverter() {
this.setsize(180,90);
this.borderstyle =
formborderstyle.fixeddialog;
this.text =" +c -> +f / +f -> +c ";
this.startposition =
formstartposition.centerscreen;
this.helpbutton = false;
this.maximizebox = false;
}
public static void main() {
application.run( new tempconverter() );
}
}
以上只有 main() 方法所在行是新的代碼。
application.run(new tempconverter());
上面這一行的意思是用新表單來啟動應用程序。
假設源文件叫做tempconverter.cs,那么執行以下的命令編譯代碼:
csc /r:system.dll /r:microsoft.win32.interop.dll /r:system.
winforms.dll tempconverter.cs
這里不再詳細講解編譯命令,因為當visual studio .net可用時,就
不必要發出命令行的編譯命令了。
第二步 向表單中增加控件
接著的一步是向表單中增加控件。我們為每個控件創建一個實例變
量,對這些新實例變量進行初始化,最后把每個控件都放在表單中。
這里是增加了控件之后表單的樣子,以及更新過的代碼:
public class tempconverter : system.winforms.form
{
label ltempfah = new label();
label ltempcel = new label();
textbox ttempfah = new textbox();
textbox ttempcel = new textbox();
button bnctof = new button();
button bnftoc = new button();
public tempconverter() {
this.setsize(180,90);
this.borderstyle =
formborderstyle.fixeddialog;
this.text =" +c -> +f / +f -> +c ";
this.startposition =
formstartposition.centerscreen;
this.helpbutton = false;
this.maximizebox = false;
ttempcel.tabindex = 0;
ttempcel.setsize(50,25);
ttempcel.setlocation(13,5);
ltempcel.tabstop = false;
ltempcel.text = "+c ";
ltempcel.setsize(25, 25);
ltempcel.setlocation(65,5);
ttempfah.tabindex = 1;
ttempfah.setsize(50,25);
ttempfah.setlocation(90,5);
ltempfah.tabstop = false;
ltempfah.text = "+f ";
ltempfah.setsize(25,25);
ltempfah.setlocation(142,5);
bnctof.tabindex = 2;
bnctof.text = "+c to +f ";
bnctof.setsize(70,25);
bnctof.setlocation(13,35);
bnftoc.tabindex = 3;
bnftoc.text = "+f to +c ";
bnftoc.setsize(70,25);
bnftoc.setlocation(90,35);
this.controls.add(ttempcel);
this.controls.add(ltempcel);
this.controls.add(ttempfah);
this.controls.add(ltempfah);
this.controls.add(bnctof);
this.controls.add(bnftoc);
}
以上代碼首先創建兩個標簽、兩個文本框和兩個按鈕,然后對每個控
件進行初始化并將其加入表單中。具體的含義如下:
- setsize() 初始化控件的尺寸
- setlocation() 初始化表單中控件的位置
- 設置控件的tabstop 屬性為false表示這個控件從不被聚焦
- 設置tabindex 為 x 表示當敲擊tab鍵x次后聚焦此控件
- 控件的text 屬性表示顯示在其上的文字信息
- this.controls.add() 表示在表單上放置一個控件,要快速地添
加每個控件,可以這么書寫:this.controls = new
control[] { ttempcel, ltempcel, ttempfar?.}