problem on override onpaint of custom control

OmkarHcl 206 Reputation points
2022-12-18T09:54:36.28+00:00

I have created a custom control derived from button class . I am trying to override its onpaint method but having problems in setting its text colour . Problems are the coloured text is not visible until i click the control and as i run the form it gets disappeared .

 public partial class custombutton : Button  
{  
    public custombutton()  
    {  
        InitializeComponent();  
    }         
    protected override void OnPaint(PaintEventArgs pe)  
    {  
         base.OnPaint(pe);  
        RenderRainbowText(this.Text, 'V', this);  
    }  
  public void RenderRainbowText(string Text, char keyword, Control Lb)  
    {  

        using (System.Drawing.Graphics formGraphics = this.CreateGraphics())  
        {  
            string[] chunks = Text.Split(keyword);  
            string word = keyword.ToString();  
            // USED FOR DRAWING chunk  
            SolidBrush brush = new SolidBrush(Color.Red);  
            SolidBrush[] brushes = new SolidBrush[] {  
                               new SolidBrush(Color.Black) };  
            
            float x = 0;  
            for (int i = 0; i < chunks.Length; i++)  
            {  
                formGraphics.DrawString(chunks[i], Lb.Font, brushes[0], x, 0); // brushes[i] has been replaced with brushes[0]  
                x += (formGraphics.MeasureString(chunks[i], Lb.Font)).Width;  
                //CODE TO MEASURE AND DRAW  
                if (i < (chunks.Length - 1))  
                {  
                    formGraphics.DrawString(word, Lb.Font, brush, x, 0);  
                    x += (formGraphics.MeasureString(",", Lb.Font)).Width;  
                }  
            }  
        }  
    }  

what i am trying is to change the color of a single character of the text string of the button . I have checked this code on a form before without using on usercontrol but facing problems on using custom button . Please update me .

Developer technologies | Windows Forms
Developer technologies | C#
Developer technologies | C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Castorix31 91,501 Reputation points
    2022-12-18T10:12:34.267+00:00

    Don't use CreateGraphics but use Graphics from PaintEventArgs


Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.