淺析C# WinForm控件開發前期準備
對于C# WinForm控件開發,MSDN上提供了很多使用的方法,那么這里就向你介紹對于C# WinForm控件開發的基本了解內容,C#開發WinForm控件的類型以及各自的特點。
C# WinForm控件開發的伊始:
其實C#開發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。
C# WinForm控件開發之控件(可視化的)的基本特征:
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);
- }
- }
- }
C# WinForm控件開發的基本前期需要了解的內容就向你介紹到這里,希望對你進行C# WinForm控件開發有所幫助。
【編輯推薦】