Aligner à droite le texte d'une ListBox

Il faut passer la propriété DrawMode de la ListBox à OwnerDrawFixed et ajouter le code suivant dans l'événement OnDraw :

private void listBox1_DrawItem(object sender, DrawItemEventArgs e)
{
    e.DrawBackground();
    e.DrawFocusRectangle();
 
    ListBox lb = sender as ListBox;    
 
    // Calcule les dimensions du texte
    SizeF stringSize = new SizeF();
    stringSize = e.Graphics.MeasureString(lb.Items[e.Index].ToString(), e.Font);
 
    e.Graphics.DrawString(
        lb.Items[e.Index].ToString(), 
        e.Font, 
        new SolidBrush(e.ForeColor), 
        new PointF(e.Bounds.Right - stringSize.Width, e.Bounds.Y)
    );            
}

Si ça peut faire gagner 5 minutes à quelqu'un...

Etiquettes:

Add new comment