C# 自定義控件VS用戶控件


1 自定義控件與用戶控件區別

WinForm中,

用戶控件(User Control):繼承自 UserControl,主要用於開發 Container 控件,Container控件可以添加其他Controls控件

自定義控件(Custom Control):繼承自 Control,主要用於開發windows控件的最基本的類,比如 Text,Button 控件

 

2 要開發自己的控件的幾種方法[1]

復合控件(Composite Controls):將現有的各種控件組合起來,形成一個新的控件,來滿足用戶的需求。

擴展控件(Extended Controls):就是在現有的控件基礎上,派生出一個新的控件,增加新的功能,或者修改原有功能,來滿足用戶需求。

自定義控件(Custom Controls):就是直接從System.Windows.Forms.Control類派生,也就是說完全由自己來設計、實現一個全新的控件,這是最靈活、最強大的方法,但是,對開發者的要求也是最高的。要實現一個自定義控件,必須為Control類的的OnPaint事件編寫代碼,在OnPaint事件中實現自定義控件的繪制工作。同時,還可以重寫Control類的WndProc方法,來處理底層的Windows消息。所以說,要實現一個自定義控件,對開發者的要求較高,要求開發者必須了解GDI+和Windows API的知識。

3 示例:Clock User Control[1]

源代碼

Steps:

1. 新建一個Windows控件庫項目(從UserControl派生)

2. 添加一個Timer控件,並設置屬性(Enable=True, Interval=1000)和事件 (Ticker=Time1_Tick)

1         private void timer1_Tick(object sender, EventArgs e) 2  { 3 this.Time = DateTime.Now; 4  Refresh(); 5 }

3. 重寫OnPaint事件,繪制用戶界面

圖1 重寫OnPaint事件,繪制用戶界面

 1         #region draw clock  2 private void UserClock_Paint(object sender, PaintEventArgs e)  3  {  4 Graphics dc = e.Graphics;  5 Pen pn = new Pen(ForeColor);  6 SolidBrush br = new SolidBrush(ForeColor);  7  initCoordinates(dc);  8  DrawDots(dc, br);  9  DrawHourHand(dc, pn); 10  DrawSecondHand(dc, pn); 11  DrawMinuteHand(dc, pn); 12  } 13 14 public void initCoordinates(Graphics dc) 15  { 16 if (this.Width == 0 || this.Height == 0) return; 17 dc.TranslateTransform(this.Width / 2, this.Height / 2); 18 dc.ScaleTransform(this.Height / 250F, this.Width / 250F); 19  } 20 public void DrawDots(Graphics dc, Brush brush) 21  { 22 int iSize; 23 for (int i = 0; i <= 59; i++) 24  { 25 if (i % 5 == 0) 26  { 27 iSize = 15; 28  } 29 else 30  { 31 iSize = 5; 32  } 33 dc.FillEllipse(brush, -iSize / 2, -100 - iSize / 2, iSize, iSize); 34 dc.RotateTransform(6); 35  } 36  } 37 public virtual void DrawHourHand(Graphics grfx, Pen pn) 38  { 39 GraphicsState gs = grfx.Save(); 40 grfx.RotateTransform(360.0F * Time.Hour / 12 + 30.0F * Time.Minute / 60); 41 grfx.DrawLine(pn, 0, 0, 0, -50); 42  grfx.Restore(gs); 43  } 44 public virtual void DrawMinuteHand(Graphics grfx, Pen pn) 45  { 46 GraphicsState gs = grfx.Save(); 47 grfx.RotateTransform(360.0F * Time.Minute / 60 + 6.0F * Time.Second / 60); 48 grfx.DrawLine(pn, 0, 0, 0, -70); 49  grfx.Restore(gs); 50  } 51 public virtual void DrawSecondHand(Graphics grfx, Pen pn) 52  { 53 GraphicsState gs = grfx.Save(); 54 grfx.RotateTransform(360.0F * Time.Second / 60); 55 grfx.DrawLine(pn, 0, 0, 0, -100); 56  grfx.Restore(gs); 57  } 58 #endregion
View Code

4. 生成用戶控件

5. 測試用戶控件

創建WinForm應用程序,在Toolbox添加Tab "User Control",再往其中拖入第4步中生成的自定義控件的dll文件。再把Toolbox中的用戶控件“UserControlClock”拖到界面“Form1”中,如下圖所示。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM