程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> 關於C語言 >> 用Visual C#做WinForm組件(3)

用Visual C#做WinForm組件(3)

編輯:關於C語言

五. 編譯組件:

到目前為止,我們所做的工作和正常的應用程序的內部編寫一個類沒有什麼區別,所不同的是下面的編譯過程,我們編譯的結果是創建一個庫,而不是一個應用程序。具體的編譯命令如下:

csc /r:system.Windows.forms.dll /t:library control.cs

編譯完成後,將得到組件control.dll

六. 創建一個簡單的客戶應用程序:

使用自定義的組件和使用.Net FrameWork SDK中提供的組件沒有任何區別,都是按照以下步驟來進行的:

(1).導入組件的名稱空間,在應用程序中,就是導入MyControls。具體如下:

using MyControls ;

(2).在程序中定義由此名稱空間封裝的組件:在程序中,使用了三個新的組件。具體如下:

protected LabeledTextBox name , address , zip ;

(3).設定這些組件的屬性,在程序中可以看到是如何設定組件的二個自定義的屬性的。下面語句就是介紹如何在程序中定義組件的新屬性。

name = new LabeledTextBox ( ) ;
name.Location = new System.Drawing.Point ( 5 , 5 ) ;
name.LabelText = "姓名:" ;

可見和定義其他屬性沒有什麼區別。

(4).把組件加入到窗體中。

下面就是按照以上步驟所得到的源程序代碼( sample.cs )和此代碼生成的執行文件的運行界面:

sample.cs源程序如下:
using System.Windows.Forms ;
using MyControls ;//導入組件的名稱空間
using System ;
public class Form1 : Form
{
//定義新構建的組件
protected LabeledTextBox name , address , zip ;
protected Button show ;
public Form1 ( )
{
InitializeComponent ( ) ;
}
public static void Main ( )
{
Application.Run ( new Form1 ( ) ) ;
}
public void InitializeComponent ( )
{
//創建新的組件,此組件中就封裝了標簽和文本框
name = new LabeledTextBox ( ) ;
address= new LabeledTextBox ( ) ;
zip = new LabeledTextBox ( ) ;
show= new Button ( ) ;
//設定新組件的屬性值,可以看看如何設定Text屬性和LabelText屬性
name.Location = new System.Drawing.Point ( 5 , 5 ) ;
name.LabelText = "姓名:" ;
address.Location = new System.Drawing.Point ( 5 , 35 ) ;
address.LabelText = "住址:" ;
zip.Location = new System.Drawing.Point ( 5 , 70 ) ;
zip.LabelText = "郵編:" ;
show.Location = new System.Drawing.Point ( 5 , 100 ) ;
show.Text = "顯示組件屬性值" ;
show.Size = new System.Drawing.Size (100, 25) ;
show.Click += new System.EventHandler ( show_Click ) ;
this.Text = "顯示自建組件的LabelText屬性和Text屬性值!" ;
this.Controls.Add ( name ) ;
this.Controls.Add ( address ) ;
this.Controls.Add ( zip ) ;
this.Controls.Add ( show ) ;
}
protected void show_Click ( object sender , EventArgs e )
{
string message = name.LabelText + " " + name.Text ;
message+="\n" + address.LabelText + " " + address.Text ;
message+="\n" + zip.LabelText + " " + zip.Text ;
MessageBox.Show ( message ,"組件的LabelText屬性和Text屬性值如下:") ;
}
}

經過一下編譯命令:

csc /r:control.dll sample.cs

產生的執行文件的運行界面如下:

七. 總結:

面向組件編程是以後程序設計的一個重要的方向,通過以上介紹,我們可以了解如何用Visual C#進行簡單的組件編程。在用Visual C#編寫組件程序的過程中,也可以看出,比起其他語言來說,用Visual C#編寫組件在編寫和分發的時候,程序員相對輕松了許多,不需要考慮很多問題了,而這些問題在用其他程序設計語言的時候卻是一定要考慮的。為什麼?因為Visual C#已經在底層把這些問題給處理好了。

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved