2012-08-08 73 views
2

我需要你在下面的(使用.net 3.5和Windows Forms)问题的帮助:绘制的线条上没有一个组合框显示

我只是单纯的想画上一个组合框的中间线(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的成员中未找到此类事件

谢谢。

+0

我认为你必须重写组合框的OnPaint事件并触发一个画图,你可以调用InvalidateRect – Schwarzie2478 2012-08-08 10:13:28

回答

2
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(); 
} 
+0

谢谢它的工作!你能回答另一个小问题吗?我用DrawImage替换了DrawLine,并且我想绘制动画GIF(类似等待动画),但它仅在静态中绘制,而不是动画,我可以使用什么来绘制动画图像? – Apokal 2012-08-08 11:04:07

+0

我认为你应该使用一个PictureBox,如[早期问题]中所述(http://stackoverflow.com/questions/165735/how-do-you-show-animated-gifs-on-a-windows-form-c )。 – 2012-08-08 11:25:50

1

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

可以得出自己所选的项目区域这种方式。

+0

谢谢!你的答案也有效! – Apokal 2012-08-08 11:04:43