我本人不是專業的控制項開發人員,只是在平常的工作中,需要自己開發一些控制項。在自己開發WinForm控制項的時候,沒有太多可以借鑒的資料,只能盯著MSDN使勁看,還好總算有些收穫。現在我會把這些經驗陸陸續續的總結出來,寫成一系列方章,希望對看到的朋友有所協助。今天我來開個頭。
其實開發WinForm控制項並不是很複雜,.NET為我們提供了豐富的底層支援。如果你有MFC或者API圖形介面的開發經驗,那麼學會WinForm控制項可能只需要很短的時間就夠了。
自己開發的WinForm控制項通常有三種類型:複合控制項(Composite Controls),擴充控制項(Extended Controls),自訂控制項(Custom Controls)。
複合控制項:將現有的各種控制群組合起來,形成一個新的控制項,將集中控制項的功能集中起來。
擴充控制項:在現有控制項的控制項的基礎上派生出一個新的控制項,為原有控制項增加新的功能或者修改原有控制項的控能。
自訂控制項:直接從System.Windows.Forms.Control類派生出來。Control類提供控制項所需要的所有準系統,包括鍵盤和滑鼠的事件處理。自訂控制項是最靈活最強大的方法,但是對開發人員的要求也比較高,你必須為Control類的OnPaint事件寫代碼,你也可以重寫Control類的WndProc方法,處理更底層的Windows訊息,所以你應該瞭解GDI+和Windows API。
本系列文章主要介紹自訂控制項的開發方法。
控制項(可視化的)的基本特徵:
1. 可視化。
2. 可以與使用者進行互動,比如通過鍵盤和滑鼠。
3. 暴露出一組屬性和方法供開發人員使用。
4. 暴露出一組事件供開發人員使用。
5. 控制項屬性的可持久化。
6. 可發布和可重用。
這些特徵是我自己總結出來,不一定準確,或者還有遺漏,但是基本上概括了控制項的主要方面。
接下來我們做一個簡單的控制項來增強一下感性認識。首先啟動VS2005建立一個ClassLibrary工程,命名為CustomControlSample,VS會自動為我們建立一個solution與這個工程同名,然後刪掉自動產生的Class1.cs檔案,最後在Solution explorer裡右鍵點擊CustomControlSample工程選擇Add->Classes…添加一個新類,將檔案的名稱命名為FirstControl。下邊是代碼:
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.ComponentModel;
using System.Drawing;
namespace CustomControlSample
{
public class FirstControl : Control
{
public FirstControl()
{
}
// ContentAlignment is an enumeration defined in the System.Drawing
// namespace that specifies the alignment of content on a drawing
// surface.
private ContentAlignment alignmentValue = ContentAlignment.MiddleLeft;
[
Category("Alignment"),
Description("Specifies the alignment of text.")
]
public ContentAlignment TextAlignment
{
get
{
return alignmentValue;
}
set
{
alignmentValue = value;
// The Invalidate method invokes the OnPaint method described
// in step 3.
Invalidate();
}
}
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
StringFormat style = new StringFormat();
style.Alignment = StringAlignment.Near;
switch (alignmentValue)
{
case ContentAlignment.MiddleLeft:
style.Alignment = StringAlignment.Near;
break;
case ContentAlignment.MiddleRight:
style.Alignment = StringAlignment.Far;
break;
case ContentAlignment.MiddleCenter:
style.Alignment = StringAlignment.Center;
break;
}
// Call the DrawString method of the System.Drawing class to write
// text. Text and ClientRectangle are properties inherited from
// Control.
e.Graphics.DrawString(
Text,
Font,
new SolidBrush(ForeColor),
ClientRectangle, style);
}
}
}
晚了,今天寫到這裡,下一篇文章介紹怎樣使用我們寫好的控制項。