How can I make a transparent tabPage?

2019-01-29 00:58发布

问题:

How can I make a transparent tabPage? I found solutions like set both Form's BackColor and TransparencyKey to a color like Color.LimeGreen or override OnPaintBackground with a empty method but TabPage doesn't have neither TransparencyKeyproperty norOnPaintBackground` method. How can I do that?

回答1:

TabControl is a native Windows component, it always draws the tab pages opaque with no built-in support for transparency. Solving this requires a little helping of out-of-the-box thinking, a tab control with transparent tab pages simply devolves to just the tabstrip being visible. All you have to do is use panels to host the controls that are now on the tab pages and make the correct one visible with the SelectedIndexChanged event.

Best to stick this in a derived class so you can still use the tab control normally at design time. Add a new class to your project and paste the code shown below. Compile. Drop the new control from the top of the toolbox onto the form, replacing the existing one.

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;

class TransparentTabControl : TabControl {
    private List<Panel> pages = new List<Panel>();

    public void MakeTransparent() {
        if (TabCount == 0) throw new InvalidOperationException();
        var height = GetTabRect(0).Bottom;
        // Move controls to panels
        for (int tab = 0; tab < TabCount; ++tab) {
            var page = new Panel {
                Left = this.Left, Top = this.Top + height,
                Width = this.Width, Height = this.Height - height,
                BackColor = Color.Transparent,
                Visible = tab == this.SelectedIndex
            };
            for (int ix = TabPages[tab].Controls.Count - 1; ix >= 0; --ix) {
                TabPages[tab].Controls[ix].Parent = page;
            }
            pages.Add(page);
            this.Parent.Controls.Add(page);
        }
        this.Height = height /* + 1 */;
    }

    protected override void OnSelectedIndexChanged(EventArgs e) {
        base.OnSelectedIndexChanged(e);
        for (int tab = 0; tab < pages.Count; ++tab) {
            pages[tab].Visible = tab == SelectedIndex;
        }
    }

    protected override void Dispose(bool disposing) {
        if (disposing) foreach (var page in pages) page.Dispose();
        base.Dispose(disposing);
    }
}

Call the MakeTransparent() method in the form's Load event handler:

private void Form1_Load(object sender, EventArgs e) {
    transparentTabControl1.MakeTransparent();
}