对C#中的TreeView添加背景图
[[wiki]wiki[/wiki]][/wiki]在[wiki]微软[/wiki]的
.NET
的Forms窗口控件中,比如Treeview和ListView,仅仅是对通用控件的简单封装,因此他们不正常的引发Paint事件。 微软所发布内容中,能看到的唯一建议就是设置控件的ControlStyles.UserPaint[wiki]类[/wiki]型,然后自己为控件做所有的绘图操作。 (译注:老外提供了一个TreeViewWithPaint控件类,派生自TreeView类,提供了Paint事件的挂接。) 一、为了解决这个问题,我们在类内部使用了一个基于Bitmap类的Graphics[wiki]对象[/wiki]。当任何窗口重新定义大小时候,对象都会重建。 //Recreate inte[wiki]RNA[/wiki]l graphics [wiki]object[/wiki]protected override void OnResize( System.EventArgs e ) { if( internalBitmap == null || internalBitmap.Width != Width || internalBitmap.Height != Height ) { if( Width != 0 && Height != 0 ) { Dis[wiki]POS[/wiki]eInternal(); internalBitmap = new Bitmap( Width, Height ); internalGraphics = Graphics.FromImage( internalBitmap ); } }} 二、重写窗口过程 当控件收到了WM_PAINT消息时候,将执行下面的三个步骤: 1. 通过一个内部的WM_PRIN[wiki]TCL[/wiki]IENT消息,让原来的控件过程把图象画到内部的Graphics对象上。 //Draw Internal GraphicsIntPtr hdc = internalGraphics.GetHdc();Message printClientMessage = Message.Create( Handle, WM_PRINTCLIENT, hdc, IntPtr.Zero ); DefWndProc( ref printClientMessage );internalGraphics.ReleaseHdc( hdc ); 2. 使用内部的Graphics对象建立PaintEventArgs参数,引发用户的OnPaint()函数。 //Add the missing OnPaint() callOnPaint( new PaintEventArgs( internalGraphics, Rectangle.FromLTRB( updateRect.left,updateRect.top,updateRect.right,updateRect.bot[wiki]Tom[/wiki] ) ) ); 3. 把内部Graphics对象的位图拷贝到屏幕的Graphics设备上。//Draw Screen GraphicsscreenGraphics.DrawImage( internalBitmap, 0, 0 );WM_ERASEBKGND消息被过滤掉,什么都不做。 case WM_ERASEBKGND://removes flickerreturn; 三、所提供的代码和[wiki]测试[/wiki][wiki]程序[/wiki]能使用Paint事件在TreeNode在被选中礫wiki]氖[/wiki]焙颍谄浔呖蛏匣龌粕谋呖颉5牵涫刀杂谖沂导室玫南钅坷此担枰砑颖尘巴嫉墓δ苊挥惺迪帧6饫锢胛颐堑哪康幕褂幸徊街#颐嵌郧拔幕嫱脊