如何将图片框的边框置于最前面?

How to Bring the Border of a Picturebox to Front?

我通过简单地在图片框周围绘制一个矩形来围绕图片框制作边框。但是由于图片框后面有一个面板,我看不到图片框周围的边框(尽管我已经在图片周围绘制了边框。代码如下:

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();
    }

这里有几处错误。首先,您在表单上绘制,该表单被您提到的面板覆盖,其次,您只在 Load 事件中绘制一次边框,而不是每次表单收到WM_PAINT 留言。

请参阅 here 以了解后者为何错误的解释。

至于在正确的位置绘制边框,为什么不直接将包含 PictureBox 的面板的 BackColor 设置为 Color.Blue 并给该面板一个非零值Padding? (或者,如果面板包含其他控件,则只为边框添加一个中间面板。)

你可以试试这个..但它会在图片框内绘制

 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);


        }

完整的解决方案是这样的。 将此 class 添加到您的应用程序中并构建应用程序。

  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));
        }
    }

构建应用程序后,您将在工具箱中看到新控件 "PicExt"。 用 PicExt 控件替换 pictureBox 并像这样订阅点击事件。

 private void button1_Click(object sender, EventArgs e)
        {
            //set the color here
            picExt1.BorderColor = Color.Red;
            //and frame width 
            picExt1.BorderWidth = 5;
        }

它应该完全按照您的要求工作。