Question

I'm trying to create a custom tab control, and it works, but there are only two things that I can't get working.

The first problem; I'm trying to add a filled rectangle before the tab that's selected, but when I select an other tab it stays at the first tab.

The second problem; This isn't really a problem but is it possible to change the width of those tabitems?

The problem

And here is the code ofcourse;

        protected override void OnPaint(System.Windows.Forms.PaintEventArgs e)
    {
        System.Drawing.Bitmap b = new System.Drawing.Bitmap(Width, Height);
        System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(b);
        g.Clear(System.Drawing.Color.FromArgb(246, 247, 249));

        for (int i = 0; i <= TabCount - 1; i++)
        {
            System.Drawing.Rectangle tabRectangle = GetTabRect(i);
            if (SelectedIndex == i)
            {
                //tab is selected
                System.Drawing.SolidBrush lightBlue = new System.Drawing.SolidBrush(System.Drawing.Color.FromArgb(239, 242, 247));
                g.FillRectangle(lightBlue, tabRectangle);

                // I can't get this working..
                System.Drawing.SolidBrush sele = new System.Drawing.SolidBrush(System.Drawing.Color.FromArgb(65, 95, 155));
                g.FillRectangle(sele, new System.Drawing.Rectangle(0, 0, 5, 32));
            }
            else
            {
                //tab is not selected
                g.FillRectangle(System.Drawing.Brushes.White, tabRectangle);
            }

            System.Drawing.SolidBrush fontColor = new System.Drawing.SolidBrush(System.Drawing.Color.FromArgb(100, 99, 104));

            g.DrawString(TabPages[i].Text, Font, fontColor, tabRectangle, new System.Drawing.StringFormat { Alignment = System.Drawing.StringAlignment.Near, LineAlignment = System.Drawing.StringAlignment.Center });
        }

        e.Graphics.DrawImage(b, 0, 0);
        b.Dispose();
        g.Dispose();
        base.OnPaint(e);
    }

Thanks.

Was it helpful?

Solution

You need to change the position of the second rectangle so it starts in the same position as the first:

//tab is selected
System.Drawing.SolidBrush lightBlue = new System.Drawing.SolidBrush(System.Drawing.Color.FromArgb(239, 242, 247));
g.FillRectangle(lightBlue, tabRectangle);

// I can't get this working..
System.Drawing.SolidBrush sele = new System.Drawing.SolidBrush(System.Drawing.Color.FromArgb(65, 95, 155));
g.FillRectangle(sele, new System.Drawing.Rectangle(
     tabRectangle.X,tabRectangle.Y,
     5, 32));

OTHER TIPS

You need to call Invalidate() to force the control to redraw.
This will re-trigger the OnPaint call.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top