2

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!

Donal23
  • 41
  • 3
  • You can set the UseCompatibleTextRendering property to true, then use the TextAlign property. – Mikael Aug 13 '20 at 20:31
  • 1
    TextAlign doesn't support Block alignment. With fixed fonts you can fake it. - Or combine the Text with ownerdrawing the right aligned text : `using (StringFormat sf = new StringFormat() { Alignment = StringAlignment.Far, LineAlignment = StringAlignment.Center }) e.Graphics.DrawString("sadasdasdasdasdas", Font, Brushes.DarkGoldenrod, button4.ClientRectangle, sf);` – TaW Aug 13 '20 at 20:40

1 Answers1

2

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.

quaabaam
  • 1,808
  • 1
  • 7
  • 15
  • Do put the Brushes into a using clause, please. Also, for even better quality TextRenderer is recommended when painting controls.. – TaW Aug 14 '20 at 01:11
  • Awesome! Thanks so much, I love that I can even set the color of the different sides :) TaW, I modifed the code based on your comment such that it now looks like: using (SolidBrush leftTextBrush etc etc) { using (SolidBrush rightTextBrush etc etc) { using (StringFormat sf... etc Is that right? Thanks! Err it doesn't save CR. I have them on their own lines actually. – Donal23 Aug 14 '20 at 02:18