C#通过重写Panel改变边框颜色与宽度的方法
本文实例讲述了C#通过重写Panel改变边框颜色与宽度的方法。分享给大家供大家参考。具体实现方法如下:
usingSystem;
usingSystem.Collections.Generic;
usingSystem.Text;
usingSystem.Runtime.InteropServices;
usingSystem.ComponentModel;
usingSystem.Windows.Forms;
usingSystem.Drawing;
namespaceImageStudio
{
publicclassPanelEx:System.Windows.Forms.Panel
{
[DllImport("user32.dll")]
privatestaticexternIntPtrGetWindowDC(IntPtrhwnd);
[DllImport("user32.dll")]
privatestaticexternintReleaseDC(IntPtrhwnd,IntPtrhdc);
privateColor_borderColor=Color.Black;
privateint_borderWidth=1;
//
//摘要:
//获取或设置控件的边框颜色。
//
//返回结果:
//控件的边框颜色System.Drawing.Color。默认为System.Drawing.Color.Black
//属性的值。
[Description("组件的边框颜色。"),Category("Appearance")]
publicColorBorderColor
{
get
{
return_borderColor;
}
set
{
_borderColor=value;
this.Invalidate();
}
}
//
//摘要:
//获取或设置控件的边框宽度。
//
//返回结果:
//控件的边框宽度int。默认为1
//属性的值。
[Description("组件的边框宽度。"),Category("Appearance")]
publicintBorderWidth
{
get
{
return_borderWidth;
}
set
{
_borderWidth=value;
this.Invalidate();
}
}
publicPanelEx()
{
SetStyle(ControlStyles.DoubleBuffer,true);
SetStyle(ControlStyles.AllPaintingInWmPaint,false);
SetStyle(ControlStyles.ResizeRedraw,true);
SetStyle(ControlStyles.UserPaint,true);
SetStyle(ControlStyles.SupportsTransparentBackColor,true);
this.Paint+=newPaintEventHandler(PanelEx_Paint);
}
privatevoidPanelEx_Paint(objectsender,PaintEventArgse)
{
if(this.BorderStyle==BorderStyle.FixedSingle)
{
IntPtrhDC=GetWindowDC(this.Handle);
Graphicsg=Graphics.FromHdc(hDC);
ControlPaint.DrawBorder(
g,
newRectangle(0,0,this.Width,this.Height),
_borderColor,
_borderWidth,
ButtonBorderStyle.Solid,
_borderColor,
_borderWidth,
ButtonBorderStyle.Solid,
_borderColor,
_borderWidth,
ButtonBorderStyle.Solid,
_borderColor,
_borderWidth,
ButtonBorderStyle.Solid);
g.Dispose();
ReleaseDC(Handle,hDC);
}
}
}
}
希望本文所述对大家的C#程序设计有所帮助。