有颜色的世界:C# listbox的item颜色改变方法

大家都喜欢多彩的世界,笔者也想运用键盘来敲出一个多彩的画面,下面给大家介绍一种C# listbox的item颜色改变的方法。

(1)C# listbox实现变色之前,需要先设置属性:

该事件由所有者描述的ListBox使用。仅当DrawMode属性设置为DrawMode.OwnerDrawFixed或DrawMode.OwnerDrawVariable时,才引发该事件。可以使用该事件来执行在ListBox中绘制项所需的任务。

如果具有大小可变的项(当DrawMode属性设置为DrawMode.OwnerDrawVariable时),在绘制项前,引发MeasureItem事件。可以为MeasureItem事件创建事件处理程序,以在DrawItem事件的事件处理程序中指定要绘制的项的大小。有关处理事件的更多信息,请参见使用事件。

(2)重写C# listbox的drawitem事件

 
 
 
  1. privatevoidlistBox1_DrawItem(objectsender,System.Windows.Forms.DrawItemEventArgse){//SettheDrawModepropertytodrawfixedsizeditems.  
  2. listBox1.DrawMode=DrawMode.OwnerDrawFixed;  
  3. //DrawthebackgroundoftheListBoxcontrolforeachitem.  
  4. e.DrawBackground();//Definethedefaultcolorofthebrushasblack.  
  5. BrushmyBrush=Brushes.Black;  
  6. //Determinethecolorofthebrushtodraweachitembasedontheindexoftheitemtodraw.  
  7. switch(e.Index){case0:myBrush=Brushes.Red;break;  
  8. case1:myBrush=Brushes.Orange;break;  
  9. case2:myBrush=Brushes.Purple;break;}  
  10. //DrawthecurrentitemtextbasedonthecurrentFontandthecustombrushsettings.  
  11. e.Graphics.DrawString(listBox1.Items[e.Index].ToString(),e.Font,myBrush,  
  12. e.Bounds,StringFormat.GenericDefault);  
  13. //IftheListBoxhasfocus,drawafocusrectanglearoundtheselecteditem.  
  14. e.DrawFocusRectangle();}   

(3)从C#  listbox的item颜色改变的例子中,我们发现在c#下面重画控件,比在vc++6.0中定义自绘方便多了。

【编辑推荐】

  1. 解析C# Socket编程实现访问网络的原理
  2. C# switch语句简单描述
  3. C# ServiceController类剖析
  4. C#抓取网页程序的实现浅析
  5. C#内存管理详细分析
THE END