0

I Have an AutoSized textbox which adjust its size according to the MeasureString of the text inside it by using this code:

private void txt_TextChanged(object sender, EventArgs e)
{
    int xold = txt.Width;
    SizeF MessageSize = txt.CreateGraphics().MeasureString(txt.Text,txt.Font);
    txt.Width = (int)MessageSize.Width + txt.Margin.Left;
    decimal hei = Math.Ceiling((decimal)MessageSize.Height);
    int h = (int)hei;
    txt.Height = h;
    int xnew = txt.Width;
    if(xold > xnew) { txt.Left += xold - xnew; }
    else { txt.Left -= xnew - xold; }
    if (txt.Width == 0) MainPanel.Controls.Remove(txt);
}

it's on a panel that have a background-image so when I start typing it starts flickering a lot. I tried to enable DoubleBufferd from Form_Properties and tried to fix it like:

protected override CreateParams CreateParams
        {
            get
            {
                var parms = base.CreateParams;
                parms.Style &= ~0x02000000;
                return parms;
            }
        }

And it does not seem to help, Any ideas appreciated how to avoid flickering when typing in the textbox. Thanks !

hB0
  • 1,977
  • 1
  • 27
  • 33
SY7K ْ
  • 11
  • 2
  • Can you use a picture box inside the panel instead of a background image. I cant quite recreate what your describing but your text box works pretty well on top of a picture box but not on top of a panel with a backgorund image. No idea why! – Kieran501 Jan 05 '21 at 11:02
  • @Kieran501 Great idea i didn't think about it , Thanks – SY7K ْ Jan 05 '21 at 12:47
  • 1
    @Kieran501 Because the [PictureBox](https://referencesource.microsoft.com/#system.windows.forms/winforms/managed/system/winforms/PictureBox.cs,128) is double-buffered by default. The [Panel](https://referencesource.microsoft.com/#system.windows.forms/winforms/Managed/System/WinForms/Panel.cs,50) is not. So, you need to derive a new class from `Panel` to enable the double-buffered feature in the constructor. – dr.null Jan 05 '21 at 14:03
  • @SY7Kْ Use the `TextRenderer.MeasureText(..)`, like [this](https://stackoverflow.com/a/8048509/14171304). – dr.null Jan 05 '21 at 14:08

0 Answers0