Delphi32.com - Home!
| Home/News | Downloads | Forums | D32 Magazine | Resources | Info and Facts |  
 
 Limiting the amount of text entered in a TEdit


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?   

    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 TForm .FormCreate(Sender: TObject);
    var
      cRect : TRect;
      bm : TBitmap;
      s : string;
    begin
      Windows.GetClientRect(Edit .Handle, cRect);
      bm := TBitmap.Create;
      bm.Width := cRect.Right;
      bm.Height := cRect.Bottom;
      bm.Canvas.Font := Edit .Font;
      s := 'W';
      while bm.Canvas.TextWidth(s) < CRect.Right do
        s := s + 'W';
      if length(s) >   then begin
        Delete(s,  ,  );
        Edit .MaxLength := Length(s);
      end;
    end;

    {Alternatively}

    procedure TForm .Edit KeyPress(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(Edit .Handle, cRect); bm := TBitmap.Create; bm.Width := cRect.Right; bm.Height := cRect.Bottom; bm.Canvas.Font := Edit .Font; if bm.Canvas.TextWidth(Edit .Text + Key) > CRect.Right then begin Key := #0; MessageBeep(- ); end; bm.Free; end; end;

     



  << Previous Faq     Complete List     Next Faq >>  



 
 Hits/month  2,500,000+ 
 Downloads
 (Since May 2000)
 7,393,709 
 Total Files  6,023 
 Forum msgs  7,670 
 Articles/FAQs  70+/900+ 
Kylix
Tips n Tricks
FAQs
Knowledge Base
Bug Listings
Articles
Books
Newsgroups
Links
Submissions
Testimonials
Advertising
Contact Us
About Us
Search Amazon:
Top Selling Software at Amazon

| Home/News | Downloads | Forums | Resources | Info and Facts | Testimonials |
  Site Search:
 


Comments/Problems: Webmaster@delphi32.com
Copyright © 1998-2006, Delphi32.com. All rights reserved.
Terms of Use