在ListBox周围绘制边框

时间:2014-11-13 03:48:34

标签: c# winforms

如何在列表框周围绘制具有指定宽度和颜色的边框? 这可以在不覆盖OnPaint方法的情况下完成吗?

3 个答案:

答案 0 :(得分:1)

您可以在面板中放置一个列表框,并将面板用作边框。面板背景色可用于创建彩色边框。这不需要太多代码。在表单组件周围使用彩色边框可以是传达状态的有效方式。

答案 1 :(得分:1)

根据Neutone的建议,这是一个方便的功能,可以在任何控件周围添加和删除基于Panel的边框,即使它是嵌套的。

只需传递您想要的Color和尺寸,如果您想要BorderStyle。要删除它,请传递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);
    }
}

答案 2 :(得分:1)

ListBox控件的问题在于它不会引发OnPaint方法,因此您不能使用它在控件周围绘制边框。

有两种方法可以在ListBox周围绘制自定义边框:

  1. 在构造函数中使用SetStyle(ControlStyles.UserPaint, True),然后可以使用OnPaint方法绘制边框。

  2. 覆盖WndProc方法,该方法处理消息结构中标识的操作系统消息。

我使用了最后一种方法在控件周围绘制自定义边框,这样就无需使用Panel为ListBox提供自定义边框。

public partial class MyListBox : ListBox
{
    public MyListBox()
    {

        // SetStyle(ControlStyles.UserPaint, True)
        BorderStyle = BorderStyle.None;
    }

    protected override void WndProc(ref Message m)
    {
        base.WndProc(m);
        var switchExpr = m.Msg;
        switch (switchExpr)
        {
            case 0xF:
                {
                    Graphics g = this.CreateGraphics;
                    g.SmoothingMode = Drawing2D.SmoothingMode.Default;
                    int borderWidth = 4;
                    Rectangle rect = ClientRectangle;
                    using (var p = new Pen(Color.Red, borderWidth) { Alignment = Drawing2D.PenAlignment.Center })
                    {
                        g.DrawRectangle(p, rect);
                    }

                    break;
                }

            default:
                {
                    break;
                }
        }
    }
}
相关问题