📄 9.2.txt
字号:
Listing 9.2 The TemperatureGauge Control Using the OnPaint Method to Render
a Thermometer
using System;
using System.Collections;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Windows.Forms;
namespace _3_CustomControl
{
public class TemperatureGauge : System.Windows.Forms.Control
{
private System.ComponentModel.Container components = null;
private int percent = 50;
public TemperatureGauge()
{
// This call is required by the Windows.Forms Form Designer.
InitializeComponent();
}
protected override void Dispose( bool disposing )
{
if( disposing )
{
if( components != null )
components.Dispose();
}
base.Dispose( disposing );
}
private void InitializeComponent()
{
}
protected override void OnPaint(PaintEventArgs pe)
{
// compute rects
Rectangle gaugeRect = new Rectangle( this.Width/6, 0,
this.Width-(2*this.Width/6), this.Height-(this.Height/10) );
Rectangle bulbRect = new Rectangle(0, this.Height-(this.Height/5),
this.Width-2, this.Height/5-2);
Rectangle emptyRect = new Rectangle( gaugeRect.X, gaugeRect.Y,
gaugeRect.Width, (gaugeRect.Height/100)*(100-percent));
Rectangle filledRect = new Rectangle( gaugeRect.X,
emptyRect.Y+emptyRect.Height, gaugeRect.Width,
gaugeRect.Height-emptyRect.Height );
// draw gauge
pe.Graphics.FillEllipse( new SolidBrush( Color.Red ), bulbRect );
pe.Graphics.DrawRectangle( new Pen(new SolidBrush( Color.Red )),
emptyRect );
pe.Graphics.FillRectangle( new SolidBrush( Color.Red ), filledRect );
// draw ticks
for( int i = 1; i < 10; i ++ )
{
pe.Graphics.FillEllipse( new SolidBrush( Color.Black ),
gaugeRect.X, (gaugeRect.Height/100)*(10*i),
gaugeRect.Width/3, 3 );
}
base.OnPaint(pe);
}
protected override void OnSizeChanged(EventArgs e)
{
base.OnSizeChanged (e);
Invalidate();
}
public int Percentage
{
get
{
return percent;
}
set
{
if( value < 0 || value > 100 )
return;
percent = value;
Invalidate();
}
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -