如何使tabControl1.DrawItem在C#中为背景使用特定颜色?

时间:2015-12-09 21:33:38

标签: c# custom-controls controls

我按照说明here创建了侧对齐标签控件。但是如果我改变表单本身的背景颜色,我会在tabControl中留下白色区域(见图片)。如何使tabControl透明或匹配表单的颜色?

enter image description here

    public Form1()
    {
        InitializeComponent();
        tabControl1.DrawItem += new DrawItemEventHandler(tabControl1_DrawItem);
    }

    private void tabControl1_DrawItem(Object sender, System.Windows.Forms.DrawItemEventArgs e)
    {
        Graphics g = e.Graphics;
        Brush _textBrush;

        // Get the item from the collection.
        TabPage _tabPage = tabControl1.TabPages[e.Index];

        // Get the real bounds for the tab rectangle.
        Rectangle _tabBounds = tabControl1.GetTabRect(e.Index);

        if (e.State == DrawItemState.Selected)
        {

            // Draw a different background color, and don't paint a focus rectangle.
            _textBrush = new SolidBrush(Color.Red);
            g.FillRectangle(Brushes.Gray, e.Bounds);
        }
        else
        {
            _textBrush = new System.Drawing.SolidBrush(e.ForeColor);
            e.DrawBackground();
        }

        // Use our own font.
        Font _tabFont = new Font("Arial", (float)10.0, FontStyle.Bold, GraphicsUnit.Pixel);

        // Draw string. Center the text.
        StringFormat _stringFlags = new StringFormat();
        _stringFlags.Alignment = StringAlignment.Center;
        _stringFlags.LineAlignment = StringAlignment.Center;
        g.DrawString(_tabPage.Text, _tabFont, _textBrush, _tabBounds, new StringFormat(_stringFlags));
    }

1 个答案:

答案 0 :(得分:-1)

在Windows窗体中,您可以停靠特定的锚点。如果将点与父窗口对接,则应消除这些间隙。