且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在 ListBox 周围绘制边框

更新时间:2023-11-12 09:59:28

按照 Neutone 的建议,这里有一个方便的函数来添加和删除任何控件周围的基于 Panel 的边框,即使它是嵌套..

Following Neutone's suggestion, here is a handy function to add and remove a Panel-based border around any control, even if it is nested..

只需传入您想要的 Color 和大小,如果您想要 BorderStyle.要再次删除它,请传入 Color.Transparent!

Simply pass in the Color and size you want, and if you want a BorderStyle. To remove it again pass in Color.Transparent!

void setBorder(Control ctl, Color col, int width, BorderStyle style)
{
    if (col == Color.Transparent)
    {
        Panel pan = ctl.Parent as Panel;
        if (pan == null) { throw new Exception("control not in border panel!");}
        ctl.Location = new Point(pan.Left + width, pan.Top + width);
        ctl.Parent = pan.Parent;
        pan.Dispose();

    }
    else
    {
        Panel pan = new Panel();
        pan.BorderStyle = style; 
        pan.Size = new Size(ctl.Width + width * 2, ctl.Height + width * 2);
        pan.Location = new Point(ctl.Left - width, ctl.Top - width);
        pan.BackColor = col;
        pan.Parent = ctl.Parent;
        ctl.Parent = pan;
        ctl.Location = new Point(width, width);
    }
}