简体   繁体   中英

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. 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.

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. It's easy to set the background images there.

This is possible by overriding WndProc() and catch the WM_ERASEBKGND message. The control shown below does this. You will however quickly find out why the Windows Forms TreeView class doesn't do this. 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. 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);
            }
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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