Mega Code Archive

 
Categories / Delphi / VCL
 

Limiting the amount of text entered in a tedit

Question: How can I limit the amount of text that is entered into a TEdit control so the text entered does not exceed the width of the TEdit control? Answer: The following two examples demonstrate limiting the text in a edit control to the amount of text that fits in the client area of the control to avoid scrolling text. The first example sets the MaxLength property to the number of "W" characters that will fit in the control. The "W" character is chosen, since it is most likely to be the widest character in the font. This method will work well for fixed pitch fonts, but will produce less than desirable effects when using a variable width font. The second method traps the edit control's key press method, and measures the text width of the current string in the edit control and the width of the character that will be added. If the width exceeds the client area of the edit control, the key is discarded, and a MessageBeep is produced. Examples: procedure TForm1.FormCreate(Sender: TObject); var cRect : TRect; bm : TBitmap; s : string; begin Windows.GetClientRect(Edit1.Handle, cRect); bm := TBitmap.Create; bm.Width := cRect.Right; bm.Height := cRect.Bottom; bm.Canvas.Font := Edit1.Font; s := 'W'; while bm.Canvas.TextWidth(s) < CRect.Right do s := s + 'W'; if length(s) > 1 then begin Delete(s, 1, 1); Edit1.MaxLength := Length(s); end; end; {Alternatively} procedure TForm1.Edit1KeyPress(Sender: TObject; var Key: Char); var cRect : TRect; bm : TBitmap; begin if ((Ord(Key) <> VK_TAB) and (Ord(Key) <> VK_RETURN) and (Ord(Key) <> VK_LEFT) and (Ord(Key) <> VK_BACK)) then begin Windows.GetClientRect(Edit1.Handle, cRect); bm := TBitmap.Create; bm.Width := cRect.Right; bm.Height := cRect.Bottom; bm.Canvas.Font := Edit1.Font; if bm.Canvas.TextWidth(Edit1.Text + Key) > CRect.Right then begin Key := #0; MessageBeep(-1); end; bm.Free; end; end;