C# Resize textbox to fit content

前端 未结 10 715
礼貌的吻别
礼貌的吻别 2020-12-05 13:39

I\'m writing a program where the user should be able to write text in a textbox. I\'d like the textbox to resize itself, so it fit the content. I\'ve tried the following:

10条回答
  •  孤城傲影
    2020-12-05 14:00

    Graphics.Measure string you can do o PaintEventArgs, not on TextChangedEventArgs

    What I think you want is this

    System.Drawing.Font myFont = new System.Drawing.Font("Verdana", 8);
    Graphics graphics = this.CreateGraphics();
    SizeF textSize = graphics.MeasureString("This is a test", myFont);
    

    The problem is that you just cannot create a Graphics object by simply allocating it since it has no public constructor, so you should better go and use TextRenderer.MeasureText, as done in http://msdn.microsoft.com/en-us/library/y4xdbe66.aspx

    TextRenderer is less accurate because it uses GDI and Graphics uses GDI+, so maybe you should leave a little margin on the value you get from the Width property.

    Hope this helps

提交回复
热议问题