【问题标题】:Drawn line isn't shown on a combobox绘制的线未显示在组合框上
【发布时间】:2012-08-05 10:18:13
【问题描述】:

以下问题需要您的帮助(使用 .Net 3.5 和 Windows 窗体):

我只是想在位于窗体上的组合框(Windows 窗体)的中间画一条线。 我使用的代码是:

void comboBox1_Paint(object sender, PaintEventArgs e)
{
  e.Graphics.DrawLine(new Pen(Brushes.DarkBlue),
                      this.comboBox1.Location.X,
                      this.comboBox1.Location.Y + (this.comboBox1.Size.Height / 2),
                      this.comboBox1.Location.X + this.comboBox1.Size.Width,
                      this.comboBox1.Location.Y + (this.comboBox1.Size.Height / 2));
}

触发绘制事件:

private void button1_Click(object sender, EventArgs e)
{
  comboBox1.Refresh();
}

当我执行代码并按下按钮时,线条不会被绘制。在调试中,绘制处理程序处的断点没有被命中。奇怪的是在MSDN ComBox 的事件列表中有一个绘制事件,但是在 VS 2010 中,IntelliSense 在 ComboBox 的成员中没有找到这样的事件

谢谢。

【问题讨论】:

  • 我认为你必须重写组合框的 OnPaint 事件并触发绘画,你可以调用 InvalidateRect

标签: c# winforms combobox system.drawing


【解决方案1】:
public Form1() 
{
  InitializeComponent();
  comboBox1.DrawMode = DrawMode.OwnerDrawFixed;
  comboBox1.DrawItem += new DrawItemEventHandler(comboBox1_DrawItem);
}

void comboBox1_DrawItem(object sender, DrawItemEventArgs e) {
  e.DrawBackground();
  e.Graphics.DrawLine(Pens.Black, new Point(e.Bounds.Left, e.Bounds.Bottom-1),
    new Point(e.Bounds.Right, e.Bounds.Bottom-1));
  TextRenderer.DrawText(e.Graphics, comboBox1.Items[e.Index].ToString(), 
    comboBox1.Font, e.Bounds, comboBox1.ForeColor, TextFormatFlags.Left);
  e.DrawFocusRectangle();
}

【讨论】:

  • 谢谢它的工作!你能再回答一个小问题吗?我用 DrawImage 替换了 DrawLine,我想绘制动画 gif(类似于等待动画),但它仅以静态而不是动画绘制,我可以用什么来绘制动画图像?
  • 我认为你应该使用 this early question 中解释的 PictureBox。
【解决方案2】:

Paint 事件不会触发。
你想要的只有DropDownStyle == ComboBoxStyle.DropDownList

        comboBox1.DrawMode = DrawMode.OwnerDrawFixed;
        comboBox1.DropDownStyle = ComboBoxStyle.DropDownList;
        comboBox1.DrawItem += (sender, args) => 
        {
            var ordinate = args.Bounds.Top + args.Bounds.Height / 2;
            args.Graphics.DrawLine(new Pen(Color.Red), new Point(args.Bounds.Left, ordinate),
                new Point(args.Bounds.Right, ordinate));
        };

这样你就可以自己绘制选中的项目区域了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多