Reputation: 255
hi i am doing a command shell using a memo in Delphi , the problem is to detect the last line written and read the command I need to know how to detect the enter key on a memo.
as I can detect the enter key on a memo ?
Upvotes: 2
Views: 7509
Reputation: 109002
Detecting the enter key in a TMemo
control is easy. Just add an OnKeyPress
event:
procedure TForm1.Memo1KeyPress(Sender: TObject; var Key: Char);
begin
if Key = #13 then
begin
// Do something
end;
end;
Upvotes: 2
Reputation: 35
You can use OnKeyDown
event, for example:
procedure TForm.Memo1KeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if Key = VK_Return then
begin
// Your code here ...
// set Key to 0 if you do not want the key
// to be default-processed by the control...
Key := 0 ;
end;
end;
Upvotes: 3
Reputation: 23046
In the OnKeypress event you can check for certain keys and handle them as you wish yourself. The enter key is one of these keys.
procedure TForm1.Memo1KeyPress(Sender: TObject; var Key: Char);
const
ENTER = #13;
begin
case Key of
ENTER : begin
// Do something
end;
end;
end;
By default a TMemo has the WantReturns property set to TRUE. This means that as well as any response to the key press that you might implement in your code, the TMemo will still also receive the key event and add a new line to the content of the memo.
If you do not want this then you can either:
OR
An example of this latter approach might look something like this:
const
NO_KEY = #0;
ENTER = #13;
begin
case Key of
ENTER : begin
// Do something
if NOT AddNewLine then
Key := NO_KEY;
end;
end;
end;
NOTE: The OnKeyPress event only allows you to respond to a subset of key events, specifically those that correspond to CHAR type values (although this does include some non-printing characters such as Tab and Backspace, for example).
If you want or need to detect the state of a wider range of non-character keys or to reliably handle key combinations such as Ctrl+Key or Shift+Key then you will need to query the state of those modifier keys. However, by the time you are responding to the key event, the state of the modifier keys may have changed and a better approach in that case is to use an alternate event which provides a greater range of key events, including the state of the Shift keys (and Control keys) at the time of the key event itself, such as OnKeyDown.
Upvotes: 11