Reputation: 13
I want to implement the keyboard shortcuts in Delphi 2010, to handle Return and Ctrl + Return in onkeyUp
event, but it seems that they are not compatible.
What I want to do with this code is : if you press Enter in an edit it adds an element in a Listbox and if you press Ctrl+Enter it should modify the active element.
My code is this:
procedure TForm5.Edit1KeyUp(Sender: TObject; var Key: Word; Shift: TShiftState);
begin
if GetKeyState(VK_RETURN) < 0 then
lb1.items[lb1.ItemIndex]:=edit1.Text;
if GetKeyState(VK_CONTROL) < 0 then
case Key of
VK_RETURN:begin
lb1.Items.Add(Edit1.text);
lb1.ItemIndex:=lb1.Items.Count-1;
label3.caption:='Nº de Registros:'+inttostr(lb1.Items.Count);
end;
and run when return and ctrl+return are used. However I don't seem to know what I'm doing wrong because I execute the code and when enter is pressed and also the code when Ctrl+enter is pressed.
Upvotes: 1
Views: 1010
Reputation: 108948
You probably want this:
procedure TForm1.Edit1KeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if Key = VK_RETURN then
begin
if ssCtrl in Shift then
ShowMessage('CONTROL: ' + Edit1.Text)
else
ShowMessage(Edit1.Text);
Key := 0;
end;
end;
(I chose to use OnKeyDown
instead of OnKeyUp
because that is the normal choice in situations like this, but it will work exactly the same way with OnKeyUp
.)
That is: if the key is Return, then act. And, act differently depending on whether the Ctrl modifier is down. Notice that there is no need to call GetKeyState
, since the event handler provides you with this information in its arguments.
Your code will malfunction because its logic is flawed.
However, the above snippet is not ideal, since Windows will produce the "invalid input beep" when you press (Ctrl+)Return.
To circumvent this, also add the following OnKeyPress
handler:
procedure TForm1.Edit1KeyPress(Sender: TObject; var Key: Char);
begin
if Key in [#13, #10] then
Key := #0;
end;
Upvotes: 3