您的位置:首页 > 其它

Winforms: 在TreeView中应用Vista Explorer的新风格

2009-05-28 10:04 120 查看
 

         从Vista开始,Windows的Explorer树型控件采用了新的风格。之前,如果在树的某结点前面有一个+或者-,用来表示该结点有子结点。而+/-表示结点的状态:+表示该结点可以打开并显示它的子结点,-表示该结点可以收缩并隐藏它的子结点。结点与它的子结点之间用虚线连接。在Vista的Explorer中,+/-被三角形所替代。三角形顶点的朝向表示结点的状态。同时,把鼠标移到某三角形上,三角形显示为蓝色表示高亮。结点和子结点之间没有虚线连接。当Explorer失去焦点的时候,所有结点前的三角形都会慢慢消失;但Explorer再次得到焦点的时候,所以结点前的三角形又会重新出现。由于在Vista的Explorer用三角形表达了更多信息,并且有一定的动画,推出之后很多Windows用户都很喜欢。
         非常遗憾的是,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的视觉效果见如下截图。

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息