Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: Pascal
Expertise: Beginner
May 13, 1997

TEdit and right-justification of text

Question:
How can I get a TEdit to display right-justified text?

Answer:
There is no way to do this at runtime because there's no facility in TEdit to right-align text. The reason is simple: In order to have right-aligned text in Windows, you have to support multiple lines! Well, an Edit control with multiple lines is really a TMemo. So you can use a TMemo to simulate a single line TEdit, without the hassle of building your own component.

There are a few things you should be aware of if you do this, though.

  1. You need to set WantReturns and WordWrap properties to False to ensure that you don't have text wrapping and that lines don't disappear when the user presses Enter.
  2. Limit the number of characters that can be entered into the TMemo with the MaxLength property.
  3. To prevent the user from inadvertently making text go away with the down arrow (assuming you've added some text to the TMemo), in the OnCreate of the form, set the SelStart property to the Length of the TMemo's text:
    Memo1.SelStart := Length(Memo1.Text);
  4. Trap for key-presses to prevent the user from using Ctrl-Enter and Ctrl-Tab, which are hard returns and hard tabs, respectively. To trap for Ctrl-Enter, write the following in the OnKeyPress event of the TMemo:

procedure TForm1.Memo1KeyPress(Sender : TObject; var Key : Char);
begin
  if Key = #10 then //Ctrl-Enter?
    Key := #0; //Kill it
end;
To trap for Ctrl-Tab, do the following in the OnKeyDown:
procedure TForm1.Memo1KeyDown(Sender : TObject; var Key : Word; Shift :
TShiftState);
begin
  if (Key = VK_TAB) AND (ssCtrl in Shift) then
    Key := 0;
end;
The reason for using both OnKeyPress and OnKeyDown is that in the first instance, I didn't need to trap a Shift state, but in the second I did need to.

This seems like a lot, but actually it's a far simpler than creating a new TEdit that will support right-justification of text. In the case of the TEdit descendant, you'd have to override the Paint method and add an alignment property that calls the Paint method when its value is changed. Sounds simple enough, but component writing is never trivial.

DevX Pro
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date