devxlogo

TEdit and right-justification of text

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 TEditto right-align text. The reason is simple: In order to have right-aligned text in Windows, you have to support multiplelines! Well, an Edit control with multiple lines is really a TMemo. So youcan use a TMemo to simulate a single line TEdit, without the hassle ofbuilding 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 toFalse 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 enteredinto the TMemo with the MaxLength property.
  3. To prevent the user from inadvertently making text go away with the downarrow (assuming you’ve added some text to the TMemo), in the OnCreate of theform, 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 usingCtrl-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 itend;
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 firstinstance, 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 thancreating a new TEdit that will support right-justification of text. In thecase of the TEdit descendant, you’d have to override the Paint method andadd an alignment property that calls the Paint method when its value ischanged. Sounds simple enough, but component writing is never trivial.

See also  5 Benefits of Using Time Tracking Software
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist