TabControl.DrawItem not firing on user painted TabControl

北战南征 提交于 2019-12-06 02:17:27

I'm not sure on this, but I believe if you specify the ControlStyles.UserPaint bit to true, then the DrawItem won't fire. The other ControlStyles (AllPaintingInWmPaint and DoubleBuffer) have dependencies on each other, though, so you would need to leave them off as well. However, not setting the UserPaint bit to true will result in the Paint event not getting fired. What I have been doing is overriding the OnPaintBackground method:

public partial class NCE_TabControl : TabControl
{
    Rectangle TabBoundary;
    RectangleF TabTextBoundary;
    StringFormat format = new StringFormat(); //for tab header text

    public NCE_TabControl()
    {   InitializeComponent();         
        this.SetStyle(ControlStyles.UserPaint | ControlStyles.AllPaintingInWmPaint | ControlStyles.DoubleBuffer, true);
        this.DrawMode = TabDrawMode.OwnerDrawFixed;
        this.format.Alignment = StringAlignment.Center;
        this.format.LineAlignment = StringAlignment.Center;
    }

    protected override void OnPaintBackground(PaintEventArgs pevent)
    {
        Graphics g = pevent.Graphics;
        g.FillRectangle(new SolidBrush(Color.Red), 0, 0, this.Size.Width, this.Size.Height);

        foreach (TabPage tp in this.TabPages)
        {
            //drawItem
            int index = this.TabPages.IndexOf(tp);

            this.TabBoundary = this.GetTabRect(index);
            this.TabTextBoundary = (RectangleF)this.GetTabRect(index);

            g.FillRectangle(new SolidBrush(Color.LightBlue), this.TabBoundary);
            g.DrawString("tabPage " + index.ToString(), this.Font, new SolidBrush(Color.Black), this.TabTextBoundary, format);
        }
    }
} 

I think this will work for you, but there may be other methods of doing it as well.

Atif

In order to get DrawItem event fired, set DrawMode = OwnerDrawFixed on the Tab Control http://msdn.microsoft.com/en-us/library/system.windows.forms.tabcontrol.drawitem.aspx

One simple way is to change the TabControl's Appearance property to either Buttons or FlatButtons and set the DrawMode badk to Normal.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!