|
我本人不是專業(yè)的控件開發(fā)人員,只是在平常的工作中,需要自己開發(fā)一些控件。在自己開發(fā)WinForm控件的時(shí)候,沒有太多可以借鑒的資料,只能盯著MSDN使勁看,還好總算有些收獲。現(xiàn)在我會(huì)把這些經(jīng)驗(yàn)陸陸續(xù)續(xù)的總結(jié)出來(lái),寫成一系列方章,希望對(duì)看到的朋友有所幫助。今天我來(lái)開個(gè)頭。
其實(shí)開發(fā)WinForm控件并不是很復(fù)雜,.NET為我們提供了豐富的底層支持。如果你有MFC或者API圖形界面的開發(fā)經(jīng)驗(yàn),那么學(xué)會(huì)WinForm控件可能只需要很短的時(shí)間就夠了。
自己開發(fā)的WinForm控件通常有三種類型:復(fù)合控件(Composite Controls),擴(kuò)展控件(Extended Controls),自定義控件(Custom Controls)。
復(fù)合控件:將現(xiàn)有的各種控件組合起來(lái),形成一個(gè)新的控件,將集中控件的功能集中起來(lái)。
擴(kuò)展控件:在現(xiàn)有控件的控件的基礎(chǔ)上派生出一個(gè)新的控件,為原有控件增加新的功能或者修改原有控件的控能。
自定義控件:直接從System.Windows.Forms.Control類派生出來(lái)。Control類提供控件所需要的所有基本功能,包括鍵盤和鼠標(biāo)的事件處理。自定義控件是最靈活最強(qiáng)大的方法,但是對(duì)開發(fā)者的要求也比較高,你必須為Control類的OnPaint事件寫代碼,你也可以重寫Control類的WndProc方法,處理更底層的Windows消息,所以你應(yīng)該了解GDI+和Windows API。 NET技術(shù):WinForm控件開發(fā)總結(jié)(一)------開篇,轉(zhuǎn)載需保留來(lái)源! 鄭重聲明:本文版權(quán)歸原作者所有,轉(zhuǎn)載文章僅為傳播更多信息之目的,如作者信息標(biāo)記有誤,請(qǐng)第一時(shí)間聯(lián)系我們修改或刪除,多謝。
本系列文章主要介紹自定義控件的開發(fā)方法。
控件(可視化的)的基本特征:
1. 可視化。
2. 可以與用戶進(jìn)行交互,比如通過(guò)鍵盤和鼠標(biāo)。
3. 暴露出一組屬性和方法供開發(fā)人員使用。
4. 暴露出一組事件供開發(fā)人員使用。
5. 控件屬性的可持久化。
6. 可發(fā)布和可重用。
這些特征是我自己總結(jié)出來(lái),不一定準(zhǔn)確,或者還有遺漏,但是基本上概括了控件的主要方面。
接下來(lái)我們做一個(gè)簡(jiǎn)單的控件來(lái)增強(qiáng)一下感性認(rèn)識(shí)。首先啟動(dòng)VS2005創(chuàng)建一個(gè)ClassLibrary工程,命名為CustomControlSample,VS會(huì)自動(dòng)為我們創(chuàng)建一個(gè)solution與這個(gè)工程同名,然后刪掉自動(dòng)生成的Class1.cs文件,最后在Solution explorer里右鍵點(diǎn)擊CustomControlSample工程選擇Add->Classes…添加一個(gè)新類,將文件的名稱命名為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);
}
}
}