繁体   English   中英

在 ListBox 周围绘制边框

[英]Draw Border around ListBox

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

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

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

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

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

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

  2. 覆盖处理 Message 结构中标识的操作系统消息的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;
                }
        }
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM