Home > database >  Why left ctrl doesn't trigger ssLeft?
Why left ctrl doesn't trigger ssLeft?

Time:03-31

I have created a very simple VCL application. It's just a form with a TMemo on it. I've added the key up event on the TMemo.

procedure TForm1.Memo1KeyUp(Sender: TObject; var Key: Word; Shift: TShiftState);
begin
  if (Key = Ord('X')) and (Shift * [ssCtrl, ssLeft] = [ssCtrl, ssLeft]) then
  begin
    ShowMessage('hi');
  end;
end;

Even though I use the left CTRL key X, it seems that the ssLeft can never be detected. Why does this happen?

CodePudding user response:

As described here:

TShiftState

the ssLeft is not a keyboard state, it's a mouse state. Ie. you are checking if the left mouse button is pressed as well as (any) Ctrl key when you press the "X" key.

In order to check if specifically the Left control key is pressed, and not (also) the right one, you need to add this to your test:

USES WinAPI.Windows;

FUNCTION KeyPressed(VirtualKey : WORD) : BOOLEAN; INLINE;
  BEGIN
    Result:=(GetKeyState(VirtualKey) AND $80000000<>0)
  END;

FUNCTION LeftCtrl : BOOLEAN; INLINE;
  BEGIN
    Result:=KeyPressed(VK_LCONTROL)
  END;

FUNCTION RightCtrl : BOOLEAN; INLINE;
  BEGIN
    Result:=KeyPressed(VK_RCONTROL)
  END;

procedure TForm1.Memo1KeyUp(Sender: TObject; var Key: Word; Shift: TShiftState);
begin
  if (Key = Ord('X')) and (Shift*[ssCtrl, ssShift, ssAlt] = [ssCtrl]) and LeftCtrl and not RightCtrl then
  begin
    ShowMessage('hi');
  end;
end;
  • Related