Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Empty a TMemo with Ctrl+Enter

What I'm trying to accomplish:

  • User enters text into a TMemo box
  • If they press Enter it creates a new line
  • If they press Ctrl+Enter it moves the text to another box and empties the TMemo

I'm using this code [KeyPreview is True]:

procedure TFMsg.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
begin
  if (Shift = [ssCtrl]) and (Key = $0D) then
  begin
    Key := 0;
    btnSendClick(Sender); //this moves the text and empties the TMemo box
  end;
end;

What's actually happening:

  • Ctrl+Enter sends the text to the other box
  • The TMemo empties but seems to accept the Enter key as the cursor sits flashing on the second line

Any help gratefully received. Thank you!

like image 966
Jon K. Avatar asked Jul 24 '13 10:07

Jon K.


1 Answers

The best way to handle this is as follows:

  1. Create an action list, or action manager, or re-use an existing one.
  2. Add an action that clears the memo and moves to the next one. You'll need to check that the active control really is a memo.
  3. Give the action the shortcut that you desire, CTRL+ENTER.

Note that you don't need to attach the action to anything. It's mere presence is enough to ensure that the shortcut will be handled.

For compound keyboard actions using modifier keys it's always simplest to use an action shortcut and so keep at arm's length from the lower level keyboard handling code.

Your action handler might look like this:

if ActiveControl is TMemo then
begin
  Memo := TMemo(ActiveControl);
  Text := Memo.Text;
  Memo.Clear;
  SelectNext(Memo, True, True);
  if ActiveControl is TMemo then
  begin
    Memo := TMemo(ActiveControl);
    Memo.Text := Text;
  end;
end;

In this code I'm assuming that there are multiple memos and the text is moved from one memo to the next one in the tab order. But your needs may well differ. In which case I'm sure it will be obvious what you need to do for your scenario.

like image 135
David Heffernan Avatar answered Nov 10 '22 15:11

David Heffernan