简体   繁体   English

如何设置TreeView控件的背景图像? (VS 2008 / .Net 3.5 / C#/ WinForms)

[英]How to set the background image of a TreeView Control? (VS 2008/.Net 3.5/C#/WinForms)

I have been doing some research and this seems to be not possible unless I start digging into InterOperabilty, ie PInvoke and what not which is not really my kettle fish. 我一直在做一些研究,除非我开始深入研究InterOperabilty(即PInvoke),否则这似乎是不可能的。 I am re posting this question as I want to know if anyone has managed to do this yet? 我要发布此问题,因为我想知道是否有人设法做到了吗?

I use .png for all my images and get a professional to provide my images so I know the images come with the best quality most appropriate formats. 我对所有图像都使用.png并请专业人员提供图像,因此我知道这些图像具有最佳质量和最合适的格式。

It seems the standard tree view control does not support a background image directly a such neither does it allow its background colour to be set to transparent? 似乎标准树视图控件不直接支持背景图像,因此也不允许将其背景色设置为透明吗? Anyone got any ideas on these two? 有人对这两个有任何想法吗?

If you're willing to use a third-party library take a look at http://objectlistview.sourceforge.net/cs/index.html - note however that it's GPL. 如果您愿意使用第三方库,请访问http://objectlistview.sourceforge.net/cs/index.html-但是请注意,它是GPL。 It's easy to set the background images there. 在此处轻松设置背景图片。

This is possible by overriding WndProc() and catch the WM_ERASEBKGND message. 这可以通过覆盖WndProc()并捕获WM_ERASEBKGND消息来实现。 The control shown below does this. 下面显示的控件将执行此操作。 You will however quickly find out why the Windows Forms TreeView class doesn't do this. 但是,您将很快找出Windows Forms TreeView类为什么不执行此操作的原因。 With the "smooth scrolling" system option turned on, you get very ugly artifacts. 启用“平滑滚动”系统选项后,您会看到非常难看的工件。 Not mentioning the lack of node text transparency. 更不用说缺乏节点文本透明度了。 No, there's no fix for that, only a complete replacement of the control that doesn't depend on the native Windows control can solve this problem. 不,没有解决方案,只有完全替换不依赖于本机Windows控件的控件才能解决此问题。 Not something you should normally consider, unless it is from a very reputable component vendor. 不是你通常应该考虑的,除非它是一个非常著名的组件供应商。

using System;
using System.Drawing;
using System.Windows.Forms;

class MyTreeView : TreeView {
    private Image mImage;
    public Image Image {
        get { return mImage; }
        set { mImage = value; Invalidate(); }
    }
    protected override void OnAfterCollapse(TreeViewEventArgs e) {
        if (mImage != null) Invalidate();
        base.OnAfterCollapse(e);
    }
    protected override void OnAfterExpand(TreeViewEventArgs e) {
        if (mImage != null) Invalidate();
        base.OnAfterExpand(e);
    }
    protected override void WndProc(ref Message m) {
        base.WndProc(ref m);
        if (m.Msg == 0x14 && mImage != null) {
            using (var gr = Graphics.FromHdc(m.WParam)) {
                gr.DrawImage(mImage, Point.Empty);
            }
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM