Home > Blockchain >  How to detect Ctrl Alt x in the keypress event handler of a VCL TMemo control?
How to detect Ctrl Alt x in the keypress event handler of a VCL TMemo control?

Time:03-24

I've created a Delphi VCL app with a single TMemo control, and this is the code I have. I use it to detect Ctrl somekey. For example, when I press Ctrl x, it pops up the alert ctrl and the Ctrl x's effect (cut) was cancelled.

function IsKeyDown(Key: Integer): Boolean;
begin
  Result := (GetAsyncKeyState(Key) and (1 shl 15) > 0);
end;

procedure TForm1.Memo1KeyPress(Sender: TObject; var Key: Char);
begin
  if IsKeyDown(VK_CONTROL) then
  begin
    ShowMessage('ctrl');
    Key := #0;
  end;

end;

However, when I changed it a little bit to this:

function IsKeyDown(Key: Integer): Boolean;
begin
  Result := (GetAsyncKeyState(Key) and (1 shl 15) > 0);
end;

procedure TForm1.Memo1KeyPress(Sender: TObject; var Key: Char);
begin
  if IsKeyDown(VK_CONTROL) and IsKeyDown(VK_MENU) then
  begin
    ShowMessage('ctrl alt');
    Key := #0;
  end;

end;

It doesn't work anymore. What I need is to detect combinations like Ctrl Alt f. I know I can use a TActionList, but I just want to know why my code doesn't work.

CodePudding user response:

You should use OnKeyDown instead, which provides you with both the key value and the modifier keys. I've demonstrated how to capture both one modifier key and multiple modifier keys in the code below.

uses
  { Needed for virtual key codes in recent Delphi versions. }
  System.UITypes;  
                 

procedure TForm1.Memo1KeyDown(Sender: TObject; var Key: Word; 
    Shift: TShiftState);
begin
  if (Key = vkX) and ([ssCtrl] = Shift) then
  begin
    Key := 0;
    ShowMessage('Got Ctrl X');
  end
  else if (Key = vkZ) and ([ssCtrl, ssAlt] = Shift) then
  begin
    Key := 0;
    ShowMessage('Got Ctrl Alt Z');
  end;
end; 
  • Related