I am making a border around a picture box by simply drawing a rectangle around it. However since there is a panel behind the picturebox, I cannot see the border around the picturebox (despite the fact that I have drawn the border around the picture. Here's the code:
private void Form1_Load(object sender, EventArgs e)
{
this.WindowState = FormWindowState.Maximized;
Graphics objGraphics = null;
objGraphics = this.CreateGraphics();
objGraphics.Clear(SystemColors.Control);
objGraphics.DrawRectangle(Pens.Blue,
ileriresmi.Left - 1, ileriresmi.Top - 1,
ileriresmi.Width + 1, ileriresmi.Height + 1);
objGraphics.Dispose();
}
There are a couple things wrong here. First, you're doing your drawing on the form, which is covered by the panel you mention, and second, you're only drawing the border once, in the Load
event, rather than every time the form receives a WM_PAINT message.
See here for an explanation of why the latter is wrong.
As for getting the border drawn in the right place, why not just set the BackColor
of the panel that holds the PictureBox
to Color.Blue
and give that panel a nonzero value for Padding
? (Or, if the panel contains other controls, add an intermediate panel just for the border.)
you may try this..but it will draw inside the picture box
private void pictureBox1_Paint(object sender, PaintEventArgs e)
{
e.Graphics.DrawRectangle(new Pen(Color.Red, 2f),0,0,pictureBox1.Size.Width-2, pictureBox1.Size.Height-2);
}
Complete solution will be like this. add this class into your application and build application.
public class PicExt : PictureBox
{
private Color _borderColor;
private int _borderWidth;
[Browsable(true)]
public Color BorderColor {
get { return _borderColor; }
set { _borderColor = value; this.Invalidate(); }
}
[Browsable(true)]
public int BorderWidth {
get { return _borderWidth; }
set { _borderWidth = value; this.Invalidate(); }
}
public PicExt()
{
_borderColor = Color.Red;
_borderWidth = 3;
}
protected override void OnPaint(PaintEventArgs pe)
{
base.OnPaint(pe);
pe.Graphics.DrawRectangle(new Pen(BorderColor, BorderWidth), BorderWidth, BorderWidth, this.Size.Width - (BorderWidth*2), this.Size.Height - (BorderWidth*2));
}
}
after building application you will see new control "PicExt" in your toolbox. replace pictureBox with PicExt Control and subscribe the click event like this.
private void button1_Click(object sender, EventArgs e)
{
//set the color here
picExt1.BorderColor = Color.Red;
//and frame width
picExt1.BorderWidth = 5;
}
it should work like exactly you want.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.