1
votes

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.

1
What exactly is the problem? Nothing happens? Compile-time error? Runtime error? Which control's event handler are you using? - Andreas Rejbrand
no . execute the code when enter is pressed and also the code when Ctrl+enter is pressed - Pedro Robles Ruiz

1 Answers

3
votes

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;