Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delphi - Detect pressing 3 keys at the same time

Tags:

delphi

I want to detect pressing 3 keys in my form for example Ctrl+C+N...the typed form I need to detect will always begin with Ctrl and next come two letters.

How I do that ?

like image 206
zac Avatar asked Feb 17 '13 21:02

zac


2 Answers

On arrival of one of the keys, you can look if the other key already has been down. E.g.:

procedure TForm1.FormKeyDown(Sender: TObject; var Key: Word;
  Shift: TShiftState);
begin
  if Shift = [ssCtrl] then begin
    case Key of
      Ord('C'):
        if (GetKeyState(Ord('N')) and $80) = $80 then
          ShowMessage('combo');
      Ord('N'):
        if (GetKeyState(Ord('C')) and $80) = $80 then
          ShowMessage('combo');
    end;
  end;
end;


However this will also detect for instance N+Ctrl+C, a sequence which does not begin with the Ctrl key. If this doesn't qualify as a valid key combination, you can keep a bit of key history with the help of a flag. The following should only detect sequences that initially begins with Ctrl:

type
  TForm1 = class(TForm)
    procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
    procedure FormKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState);
  private
    FValidKeyCombo: Boolean;
  end;

...

procedure TForm1.FormKeyDown(Sender: TObject; var Key: Word;
  Shift: TShiftState);
begin
  if FValidKeyCombo and (Shift = [ssCtrl]) then
    case Key of
      Ord('C'):
        if (GetKeyState(Ord('N')) and $80) = $80 then
          ShowMessage('combo');
      Ord('N'):
        if (GetKeyState(Ord('C')) and $80) = $80 then
          ShowMessage('combo');
    end;
  FValidKeyCombo := (Shift = [ssCtrl]) and (Key in [Ord('C'), Ord('N')]);
end;

procedure TForm1.FormKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState);
begin
  FValidKeyCombo := False;
end;
like image 69
Sertac Akyuz Avatar answered Nov 12 '22 23:11

Sertac Akyuz


There is more easy way:

    procedure TForm1.FormKeyDown(Sender: TObject; var Key: Word;  Shift: TShiftState);
     begin
         If (GetKeyState(Ord('Q'))<0) and (GetKeyState(Ord('N'))<0) and (GetKeyState(VK_CONTROL)<0)
           Then ShowMessage('You did it :)');
     End;
like image 38
Tarlan Pasha Avatar answered Nov 13 '22 00:11

Tarlan Pasha