Custom TextBox [modified]
-
Hello. Got an annoying problem here. I'm trying to create a custom TextBox which renders the text central vertically. Additionally, I want the font to reduce in size if it is wider than the TextBox so it is all visible. The problem is the text renders fine until it's too wide, then it won't draw at all. Here's the KeyPress event handler: private void TextArea_KeyPress(object sender, KeyPressEventArgs e) { if (e.KeyChar == 8) { if (baseString.Length > 0) baseString.Remove(baseString.Length - 1, 1); } else baseString.Append(e.KeyChar); if (baseString.Length == 0) { using (Graphics gfx = this.CreateGraphics()) { gfx.Clear(this.BackColor); return; } } // Setup the graphics object Graphics g = this.CreateGraphics(); g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.ClearTypeGridFit; g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; SizeF stringSize = g.MeasureString(baseString.ToString(), this.Font); if (stringSize.Width > this.Width) { while (stringSize.Width > this.Width) { this.Font = new Font(this.Font.FontFamily, this.Font.Size - 1); stringSize = g.MeasureString(baseString.ToString(), this.Font); } } else { while (stringSize.Height < (this.Height - 6)) { this.Font = new Font(this.Font.FontFamily, this.Font.Size + 1); stringSize = g.MeasureString(baseString.ToString(), this.Font); } } g.Clear(this.BackColor); float posX, posY; posX = (this.Width / 2) - (stringSize.Width / 2); posY = (this.Height / 2) - (stringSize.Height / 2); g.DrawString(baseString.ToString(), this.Font, new SolidBrush(this.ForeColor), posX, posY); g.Dispose(); } You can see the reduced size string flicker in and out when typing fairly fast but then it disappears. Any help would be appreciated. ----------------------------------------------------------------- EDIT: Realised I should have put the painting in the OnPaint method which I did, and found an unintentional loop which I've removed. It's working correctly now apart from the fact that as the text gets longer, and therefore the font smaller, my alignment veers off to the left a bit.
modified on Wednesday, September 24, 2008 9:29 AM