Set TabPage Header Color

前端 未结 4 1652
再見小時候
再見小時候 2020-11-27 06:57

Greetings,

I have a tab control and I want to have 1 of the tabs have it\'s text color changed on a event. I\'ve found answers like C# - TabPage Color event and C# W

4条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-27 07:39

    private void MainForm_Load(object sender, EventArgs e)
    {
           ...    
                    
           this.tabControl1.DrawMode = TabDrawMode.OwnerDrawFixed;
           this.tabControl1.DrawItem += new System.Windows.Forms.DrawItemEventHandler(this.tabControl1_DrawItem);
           ...
    }
    
    
    private void tabControl1_DrawItem(object sender, DrawItemEventArgs e)
    {
         try
         {   
              // Draw the background of the control for each item.
              //e.DrawBackground();
                
              if (e.Index == this.tabControl1.SelectedIndex)
              {
                  Brush _BackBrush = new SolidBrush(tabControl1.TabPages[e.Index].BackColor);
                       
    
                  Rectangle rect = e.Bounds;
                  e.Graphics.FillRectangle(_BackBrush, (rect.X) + 4, rect.Y, (rect.Width) - 4, rect.Height);
                        
                  SizeF sz = e.Graphics.MeasureString(tabControl1.TabPages[e.Index].Text, e.Font);
                  e.Graphics.DrawString(tabControl1.TabPages[e.Index].Text, e.Font, Brushes.Black,
                             e.Bounds.Left + (e.Bounds.Width - sz.Width) / 2,
                             e.Bounds.Top + (e.Bounds.Height - sz.Height) / 2 + 1);
    
             }
             else
             {   
                  // 파스톤계 배경색 없앨려면 FromArgb 를 없애면 된다.
                  Brush _BackBrush = new SolidBrush(Color.FromArgb(50, tabControl1.TabPages[e.Index].BackColor));
    
                  Rectangle rect = e.Bounds;
                  e.Graphics.FillRectangle(_BackBrush, rect.X, (rect.Y)-0, rect.Width, (rect.Height)+6);
    
                  SizeF sz = e.Graphics.MeasureString(tabControl1.TabPages[e.Index].Text, e.Font);
                  e.Graphics.DrawString(tabControl1.TabPages[e.Index].Text, e.Font, Brushes.Black, 
                  e.Bounds.Left + (e.Bounds.Width - sz.Width) / 2,
                            e.Bounds.Top + 5);
                        
             }
                
         }
         catch (Exception Ex)
         {
              MessageBox.Show(Ex.Message, "Error Occured", MessageBoxButtons.OK, MessageBoxIcon.Information);
    
         }
    }
    

提交回复
热议问题