1

We are adding an ASCII editor to our application, and we are using TRichEdit in Delphi XE7. We need to display the Row and Column in the status bar, but have not found any code that works with the Key down function. The code below is the current code we are using. The code below works perfect with the mouse down, but the key down is not consistent.

Row := SendMessage(asciieditor.Handle, EM_LINEFROMCHAR, asciieditor.SelStart, 0);    
Col := asciieditor.SelStart - SendMessage(asciieditor.Handle, EM_LINEINDEX, Row, 0);
3
  • 1
    "but the key down is not consistent" - in what way, exactly? Please be more specific. It is possible that the key hasn't actually been processed yet, thus your SelStart is not where you are expecting. Try delaying the calculation until after the OnKeyDown event has exited. Or use OnKeyUp instead. Though, for something like this task, I would probably create a TAction and assign an OnUpdate event to it to keep the status bar updated. Action OnUpdate events are fired whenever the app goes idle after message processing. Or, just use the TApplication(Events).OnIdle event. Commented Feb 28, 2022 at 19:27
  • 1
    Hello Remy. That was it. We moved the call to get the row and column from the richeditkeyup procedure and now it is updating the status bar as expected. Thanks so much for your help. Commented Feb 28, 2022 at 19:38
  • @MRoth: Now see what happens when you enter text using speech recognition! Or dragging a selection from Microsoft Word to your editor (which will not give you an OnMouseDown event). Commented Feb 28, 2022 at 20:18

1 Answer 1

2

When you want to display the caret position in a Rich Edit control in the status bar, the usual way is to use the editor's OnSelectionChange event:

procedure TForm1.RichEdit1SelectionChange(Sender: TObject);
begin
  StatusBar1.Panels[0].Text := Format('Row: %d  Col: %d',
    [RichEdit1.CaretPos.Y + 1, RichEdit1.CaretPos.X + 1]);
end;

This is fired every time the caret pos or selection end point is moved, which is precisely what you need.

Attempting to keep the status bar updated using mouse and keyboard events is not a good idea. For instance, what if the user is editing or typing without using the mouse or keyboard? (For instance, programmatically or using speech recognition.)

And using OnIdle is a waste of CPU cycles.

Sign up to request clarification or add additional context in comments.

1 Comment

Just as an FYI, TRichEdit.CaretPos is implemented using EM_EXGETSEL+EM_LINEINDEX for the X (row) coordinate, and EM_EXLINEFROMCHAR for the Y (column) coordinate. Every time the CaretPos is read, the coordinates are re-calculated. So I would suggest caching the result in a local variable.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.