非常遗憾的是,Winforms到目前为止还没有支持这种新的树状控件。不过,Winforms程序员可以自己加少量的代码在TreeView上应用新的风格。下面的Utility类就是一个例子,以应用Vista Explorer新的树状风格:
internal class Utility { const int TV_FIRST = 0x1100; const int TVM_SETEXTENDEDSTYLE = TV_FIRST + 44; const int TVM_GETEXTENDEDSTYLE = TV_FIRST + 45; const int TVS_EX_FADEINOUTEXPANDOS = 0x0040; const int TVS_EX_DOUBLEBUFFER = 0x0004; [DllImport("uxtheme.dll", CharSet = CharSet.Auto)] public extern static int SetWindowTheme(IntPtr hWnd, string subAppName, string subIdList); [DllImport("user32.dll", CharSet = CharSet.Auto)] public extern static IntPtr SendMessage(IntPtr hWnd, int Msg, IntPtr wParam, IntPtr lParam); private static int TreeView_GetExtendedStyle(IntPtr handle) { IntPtr ptr = SendMessage(handle, TVM_GETEXTENDEDSTYLE, IntPtr.Zero, IntPtr.Zero); return ptr.ToInt32(); } private static void TreeView_SetExtendedStyle(IntPtr handle, int extendedStyle, int mask) { SendMessage(handle, TVM_SETEXTENDEDSTYLE, new IntPtr(mask), new IntPtr(extendedStyle)); } // Modify a WinForms TreeView control to use the new Explorer style theme public static void ApplyTreeViewThemeStyles(TreeView treeView) { if (treeView == null) { throw new ArgumentNullException("treeView"); } treeView.HotTracking = true; treeView.ShowLines = false; IntPtr hwnd = treeView.Handle; SetWindowTheme(hwnd, "Explorer", null); int exstyle = TreeView_GetExtendedStyle(hwnd); exstyle |= TVS_EX_DOUBLEBUFFER | TVS_EX_FADEINOUTEXPANDOS; TreeView_SetExtendedStyle(hwnd, exstyle, 0); } }
在下面的例子中,在Form1中添加了两个TreeView,treeView1和treeView2。treeView1全部采用缺省的设置。treeView2同样也用缺省设置,但在Form1的构造函数的最后,调用函数Utility.ApplyTreeViewThemeStyles(treeView2)。两个TreeView的视觉效果见如下截图。