Question

I have a tabcontrol with DrawMode set to OwnerDrawFixed. I have been able to draw the tab and color it Black what i want to do is to draw a seperate paint for the selected tab and color it Gray. This is my Draw_Item event.

private void tabControl1_DrawItem(object sender, DrawItemEventArgs e)
{
    //This is the code i want to use to color the selected tab (e.Graphics.FillRectangle(Brushes.Gray, e.Bounds.X, e.Bounds.Y, 200, 32);
    e.Graphics.FillRectangle(Brushes.Black, e.Bounds.X, e.Bounds.Y, 200, 32);
    e.Graphics.DrawString("x", e.Font, Brushes.Black, e.Bounds.Right-17, e.Bounds.Top+4);
    e.Graphics.DrawString(this.tabControl1.TabPages[e.Index].Text, e.Font, Brushes.White, e.Bounds.Left + 12, e.Bounds.Top + 4);
    e.DrawFocusRectangle();
    if (e.Index == activeButton)
        ControlPaint.DrawBorder(e.Graphics, new Rectangle(e.Bounds.Right - 22, e.Bounds.Top + 4, 20, 20), Color.Blue, ButtonBorderStyle.Inset);
}

I have created a global variable TabPage current that i want to use to store the current tab page and in SelectedIndexChanged event i have assigned the selected tab to the variable and called Invalidate(); to force repaint of the tab.

private void tabControl1_SelectedIndexChanged(object sender, EventArgs e)
{
    current = tabControl1.SelectedTab;
    tabControl1.Invalidate();
}

Now where I'm stuck is how to color only the selected tab in the DrawItem event.

My Question now is how do i check for selected tab in the DrawItem event and paint only the selected tab.

Was it helpful?

Solution

I finally found the answer to my question. I modified the global variable to be of int datatype and then assigned the index to it in SelectedIndexChanged, and then checked for it in the DrawItem.

int current;
private void tabControl1_SelectedIndexChanged(object sender, EventArgs e)
{
    current = tabControl1.SelectedIndex;
    tabControl1.Invalidate();
}

private void tabControl1_DrawItem(object sender, DrawItemEventArgs e)
{
    e.Graphics.FillRectangle(Brushes.Black, e.Bounds.X, e.Bounds.Y, 200, 32);
    e.Graphics.DrawString("x", e.Font, Brushes.Black, e.Bounds.Right-17, e.Bounds.Top+4);
    e.Graphics.DrawString(this.tabControl1.TabPages[e.Index].Text, e.Font, Brushes.White, e.Bounds.Left + 12, e.Bounds.Top + 4);
    if (e.Index == activeButton)
        ControlPaint.DrawBorder(e.Graphics, new Rectangle(e.Bounds.Right - 22, e.Bounds.Top + 4, 20, 20), Color.Blue, ButtonBorderStyle.Inset);

    if (e.Index == current)
    {
        e.Graphics.FillRectangle(Brushes.Gray, e.Bounds.X, e.Bounds.Y, 200, 32); 
        e.Graphics.DrawString("x", e.Font, Brushes.Black, e.Bounds.Right - 17, e.Bounds.Top + 4);
        e.Graphics.DrawString(this.tabControl1.TabPages[e.Index].Text, e.Font, Brushes.White, e.Bounds.Left + 12, e.Bounds.Top + 4);    
    }
}

Works fine for me.

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