Multicolor text on button

ankit goel 766 Reputation points
2022-11-12T09:54:43.133+00:00

is it possible to create a custombutton whose text should be in two colors. I found out that it is possible by creating customcontrol and overriding onpaint method and using gdi+ . I am not comfortable in GDI+. Can anyone please help me in this matter

259715-micro.png

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,511 Reputation points
    2022-11-12T11:53:09.227+00:00

    A minimal test with a gradient brush (you can use different brushes/fonts to colorize letters), to be improved by adding properties for the text, background, mouse hover, etc... :

    (remove space at each On Paint, editor bug...)

    public partial class CustomButton : Button  
    {  
        protected override void On Paint(PaintEventArgs pevent)  
        {  
            Text = "";  
            base.On Paint(pevent);  
            Text = "This is a test";  
            using (Font font = new Font("Arial", 20, FontStyle.Bold, GraphicsUnit.Point))  
            {  
                using (LinearGradientBrush brush = new LinearGradientBrush(new Rectangle(0, 0, Width, Height), Color.Blue, Color.Red, LinearGradientMode.Horizontal))  
                {  
                    StringFormat stringFormat = new StringFormat();  
                    stringFormat.Alignment = StringAlignment.Center;  
                    stringFormat.LineAlignment = StringAlignment.Center;  
                    Rectangle rect = new Rectangle(0, 0, Width, Height);  
                    //pevent.Graphics.FillRectangle(new SolidBrush(Color.Yellow), rect);  
                    pevent.Graphics.DrawString(Text, font, brush, rect, stringFormat);  
                }  
            }  
        }  
    }  
    

    259716-button-onpaint.jpg

    1 person found this answer helpful.

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.