作者非專業控件開發者,但在實務中需自行開發控件,苦於資料稀少,僅能研讀 MSDN。現將經驗整理成系列,冀助同好。
| 類型 | 定義 | 特點 |
|---|---|---|
| 複合控件 | 組合現有控件形成新控件 | 整合既有功能,開發門檻較低 |
| 擴展控件 | 繼承現有控件並增強/修改功能 | 復用基礎邏輯,擴充特定行為 |
| 自定義控件 | 直接繼承 System.Windows.Forms.Control |
最靈活強大,需自行實作 OnPaint、可重寫 WndProc 處理 Windows 訊息,要求 GDI+ 與 Win32 API 基礎 |
本系列專注於自定義控件開發。
建立 Class Library 專案 CustomControlSample,新增 FirstControl.cs:
using System;
using System.Windows.Forms;
using System.ComponentModel;
using System.Drawing;
namespace CustomControlSample {
public class FirstControl : Control {
public FirstControl() { }
private ContentAlignment alignmentValue = ContentAlignment.MiddleLeft;
[Category("Alignment"), Description("Specifies the alignment of text.")]
public ContentAlignment TextAlignment {
get { return alignmentValue; }
set {
alignmentValue = value;
Invalidate(); // 觸發重繪
}
}
protected override void OnPaint(PaintEventArgs e) {
base.OnPaint(e);
StringFormat style = new StringFormat();
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;
}
e.Graphics.DrawString(Text, Font, new SolidBrush(ForeColor), ClientRectangle, style);
}
}
}
核心要點:
Control,複寫 OnPaint 進行 GDI+ 繪圖Invalidate() 觸發重繪StringFormat 控制文字對齊下一篇將介紹如何使用與偵錯這個剛寫好的控件。