如何制作透明的tabPage?

Jac*_*ack 1 c# tabcontrol transparent tabpage winforms

如何制作透明的tabPage?我找到了解决方案,例如将Form的设置BackColorTransparencyKey颜色设置为Color.LimeGreenOnPaintBackground使用空方法覆盖,但TabPage既没有TransparencyKey property norOnPaintBackground`方法.我怎样才能做到这一点?

Han*_*ant 7

TabControl是一个本机Windows组件,它总是绘制不透明的标签页,没有内置的透明支持.解决这个问题需要一些开箱即用的思考,带有透明标签页的标签控件只是简单地转移到可见的标签条.您所要做的就是使用面板来托管现在在选项卡页面上的控件,并使用SelectedIndexChanged事件使正确的控件可见.

最好将其粘贴在派生类中,这样您仍然可以在设计时正常使用选项卡控件.在项目中添加一个新类并粘贴下面显示的代码.编译.将新控件从工具箱顶部拖放到表单上,替换现有控件.

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

在窗体的Load事件处理程序中调用MakeTransparent()方法:

private void Form1_Load(object sender, EventArgs e) {
    transparentTabControl1.MakeTransparent();
}
Run Code Online (Sandbox Code Playgroud)