java 用户控件_C#自定义控件VS用户控件
C#中自定義控件VS用戶控件大比拼
1 自定義控件與用戶控件區(qū)別
WinForm中,
用戶控件(User Control):繼承自 UserControl,主要用于開發(fā) Container 控件,Container控件可以添加其他Controls控件
自定義控件(Custom Control):繼承自 Control,主要用于開發(fā)windows控件的最基本的類,比如 Text,Button 控件
2 要開發(fā)自己的控件的幾種方法[1]
復(fù)合控件(Composite Controls):將現(xiàn)有的各種控件組合起來,形成一個(gè)新的控件,來滿足用戶的需求。?
擴(kuò)展控件(Extended Controls):就是在現(xiàn)有的控件基礎(chǔ)上,派生出一個(gè)新的控件,增加新的功能,或者修改原有功能,來滿足用戶需求。
自定義控件(Custom Controls):就是直接從System.Windows.Forms.Control類派生,也就是說完全由自己來設(shè)計(jì)、實(shí)現(xiàn)一個(gè)全新的控件,這是最靈活、最強(qiáng)大的方法,但是,對(duì)開發(fā)者的要求也是最高的。要實(shí)現(xiàn)一個(gè)自定義控件,必須為Control類的的OnPaint事件編寫代碼,在OnPaint事件中實(shí)現(xiàn)自定義控件的繪制工作。同時(shí),還可以重寫Control類的WndProc方法,來處理底層的Windows消息。所以說,要實(shí)現(xiàn)一個(gè)自定義控件,對(duì)開發(fā)者的要求較高,要求開發(fā)者必須了解GDI+和Windows API的知識(shí)。
3 示例:Clock User Control[1]
源代碼
Steps:
1. 新建一個(gè)Windows控件庫項(xiàng)目(從UserControl派生)
2. 添加一個(gè)Timer控件,并設(shè)置屬性(Enable=True, Interval=1000)和事件 (Ticker=Time1_Tick)
private void timer1_Tick(object sender, EventArgs e)
{
this.Time = DateTime.Now;
Refresh();
}
3. 重寫OnPaint事件,繪制用戶界面
圖1 重寫OnPaint事件,繪制用戶界面
#region draw clock
private void UserClock_Paint(object sender, PaintEventArgs e)
{
Graphics dc = e.Graphics;
Pen pn = new Pen(ForeColor);
SolidBrush br = new SolidBrush(ForeColor);
initCoordinates(dc);
DrawDots(dc, br);
DrawHourHand(dc, pn);
DrawSecondHand(dc, pn);
DrawMinuteHand(dc, pn);
}
public void initCoordinates(Graphics dc)
{
if (this.Width == 0 || this.Height == 0) return;
dc.TranslateTransform(this.Width / 2, this.Height / 2);
dc.ScaleTransform(this.Height / 250F, this.Width / 250F);
}
public void DrawDots(Graphics dc, Brush brush)
{
int iSize;
for (int i = 0; i <= 59; i++)
{
if (i % 5 == 0)
{
iSize = 15;
}
else
{
iSize = 5;
}
dc.FillEllipse(brush, -iSize / 2, -100 - iSize / 2, iSize, iSize);
dc.RotateTransform(6);
}
}
public virtual void DrawHourHand(Graphics grfx, Pen pn)
{
GraphicsState gs = grfx.Save();
grfx.RotateTransform(360.0F * Time.Hour / 12 + 30.0F * Time.Minute / 60);
grfx.DrawLine(pn, 0, 0, 0, -50);
grfx.Restore(gs);
}
public virtual void DrawMinuteHand(Graphics grfx, Pen pn)
{
GraphicsState gs = grfx.Save();
grfx.RotateTransform(360.0F * Time.Minute / 60 + 6.0F * Time.Second / 60);
grfx.DrawLine(pn, 0, 0, 0, -70);
grfx.Restore(gs);
}
public virtual void DrawSecondHand(Graphics grfx, Pen pn)
{
GraphicsState gs = grfx.Save();
grfx.RotateTransform(360.0F * Time.Second / 60);
grfx.DrawLine(pn, 0, 0, 0, -100);
grfx.Restore(gs);
}
#endregion
4. 生成用戶控件
5. 測試用戶控件
創(chuàng)建WinForm應(yīng)用程序,在Toolbox添加Tab "User Control",再往其中拖入第4步中生成的自定義控件的dll文件。再把Toolbox中的用戶控件“UserControlClock”拖到界面“Form1”中,如下圖所示。
以上就是本文的全部內(nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
總結(jié)
以上是生活随笔為你收集整理的java 用户控件_C#自定义控件VS用户控件的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 开封看免疫性不孕症最好的医院推荐
- 下一篇: C#常用输出格式