【问题标题】:Draw Border around ListBox在列表框周围绘制边框
【发布时间】:2015-01-10 03:12:24
【问题描述】:

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

【问题讨论】:

  • 这就是 OnPaint 事件的用途.....
  • 覆盖它并绘制它可以工作,但是,我再也看不到列表框项目了。

标签: c# winforms


【解决方案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】:

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

【讨论】:

  • 事实上你可以编写一个SetBorder(Control ctl, Color color)函数,它可以创建、调整大小和放置Panel,然后将ListBox放入其中,只需几行代码.. pass null 或 Color.Transparent 用于颜色以恢复操作..
【解决方案3】:

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

【讨论】:

  • 6 年后,你来找我了 ;)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多