Donal23
Donal23

Reputation: 41

How can I align text both left and right in a C# WinForms button?

Sorry if I missed an existing post, but all the ones I see are for Android and CSS and stuff, not C#.

I am making a media manager and when I search I have a flow layout panel that populates with buttons that will launch movies matching the search. What I want to do is have button text like this (assuming pipe | is the side of the button):

| Martian, The             [4K UHD] |
| Hard Rain                 [1080p] |
| Life of Pi                   [4K] |

I can justify in one direction, but not both. Is it possible? Thanks!

Upvotes: 2

Views: 1111

Answers (1)

quaabaam
quaabaam

Reputation: 1972

One option could be to create a custom button that inherits from Button and override its OnPaint event (building on TaW's comment).

 public class DuelTextFieldButton : Button
{
    public string LeftText { get; set; }
    public string RightText { get; set; }
    public Color RightTextColor { get; set; }

    protected override void OnPaint(PaintEventArgs pevent)
    {
        base.OnPaint(pevent);

        using (SolidBrush leftTextBrush = new SolidBrush(this.ForeColor))
        {
            using (StringFormat sf = new StringFormat()
                    { Alignment = StringAlignment.Near, LineAlignment = StringAlignment.Center })
            {
                pevent.Graphics.DrawString(LeftText, this.Font, leftTextBrush, this.ClientRectangle, sf);
            }
        }

        using (SolidBrush rightTextBrush = new SolidBrush(RightTextColor))
        {
            using (StringFormat sf = new StringFormat()
                    { Alignment = StringAlignment.Far, LineAlignment = StringAlignment.Center })
            {
                pevent.Graphics.DrawString(RightText, this.Font, rightTextBrush, this.ClientRectangle, sf);
            }
        }
            
    }
}

EDIT: Added using statements to brushes, as suggested by TaW's comment.

Upvotes: 2

Related Questions