效果圖
下面的圖形,就是當ComboBox是Focused時,就會顯示邊框。
代碼
下面是一個簡單的例子,是對ComboBox的重繪,在控件Focused的時候,爲控件增加一條邊框,注意到WM_PAINT消息就是重繪的,它只是一個Windows消息,也就是簡單的一個數據,在這時,它表示15,下面,override WndProc時,增加一個邊框,this.DesignMode意思是,當前的是設計模式,如果是設計模式,就不畫了。m.Msg ==WM_PAINT,就是指捕捉重繪消息,並做出反應,Graphics.FromHwnd(Handle)意思是獲取Graphics的實例,利用ComboBox的句柄,提取出實例。
{
Color _defaultColor = SystemColors.Control;
Color _focusColor = Color.Blue;
const int WM_PAINT = 0x000F;
public ComboBox()
{
InitializeComponent();
}
///
/// 重寫WndProc方法
///
///
protected override void WndProc(ref Message m)
{
base.WndProc(ref m);
if (this.DesignMode) return;
if(m.Msg ==WM_PAINT)
{
Graphics g = Graphics.FromHwnd(Handle);
DrawBoxBorder(g);
g.Dispose();
}
}
///
/// 畫ComboBox的邊框
///
///
private void DrawBoxBorder(Graphics g)
{
Rectangle rect = this.ClientRectangle;
if (this.Focused == false || this.Enabled == false)
ControlPaint.DrawBorder(g, rect, _defaultColor, ButtonBorderStyle.Solid);
else
ControlPaint.DrawBorder(g, rect, _focusColor, ButtonBorderStyle.Solid);
}
}
ControlPaint.DrawBorder與g.DrawRectangle
是調用系統的方法來畫一個邊框,注意的是,使用這個方法與g.DrawRectangle是不同的,在使用Rectangle時,大小和位置是不同。這需要自己來體會。同時,ControlPaint.DrawBorder比後者在繪畫時更有效。