Search code examples
c#winformsautosizestatusstrip

Can StatusStrip automatically change its height depending on its items' size?


I've got a statusstrip with a number of items. One of them is a ToolStripStatusLabel with Spring = True. When the text of the label is too long, one can't see it.

Is it possible to make the statusstrip become higher and show whole text in multiline?


Solution

  • This is an interesting problem....I tried a couple of things but no success...basicall the ToolStripStatusLabel is very limited in capability.

    I ended up trying a hack that gives the result you want but am not sure even I would recommend this unless of course this is absolutely necessary...

    Here's what I have got...

    In the properties of your StatusStrip set AutoSize = false, this is to allow the StatusStrip to be resized to accommodate multiple lines. I am assuming statusStrip called ststusStrip1 containing label called toolStripStatusLabel1.

    At form Level declare a variable of TextBox type:

      TextBox txtDummy = new TextBox();
    

    At Form Load set some of its properties:

      txtDummy.Multiline = true;
      txtDummy.WordWrap = true;
      txtDummy.Font = toolStripStatusLabel1.Font;//Same font as Label
    

    Handle the paint event of the toolStripStatusLabel1

     private void toolStripStatusLabel1_Paint(object sender, PaintEventArgs e)
     {        
    
        String textToPaint = toolStripStatusLabel1.Tag.ToString(); //We take the string to print from Tag
        SizeF stringSize = e.Graphics.MeasureString(textToPaint, toolStripStatusLabel1.Font);
        if (stringSize.Width > toolStripStatusLabel1.Width)//If the size is large we need to find out how many lines it will take
        {
            //We use a textBox to find out the number of lines this text should be broken into
            txtDummy.Width = toolStripStatusLabel1.Width - 10;
            txtDummy.Text = textToPaint;
            int linesRequired = txtDummy.GetLineFromCharIndex(textToPaint.Length - 1) + 1;
            statusStrip1.Height =((int)stringSize.Height * linesRequired) + 5;
            toolStripStatusLabel1.Text = "";
            e.Graphics.DrawString(textToPaint, toolStripStatusLabel1.Font, new SolidBrush( toolStripStatusLabel1.ForeColor), new RectangleF( new PointF(0, 0), new SizeF(toolStripStatusLabel1.Width, toolStripStatusLabel1.Height)));
        }
        else
        {
            toolStripStatusLabel1.Text = textToPaint;
        }
    } 
    

    IMP: Do not assign the text property of your label instead put it in Tag we would use it from Tag

     toolStripStatusLabel1.Tag = "My very long String";
    

    Screenshot