Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delphi: Cannot capture Ctrl+C if user pressed the sequence too quickly

Tags:

delphi

I am trying to capture when a user presses Ctrl+C in order to copy some text to the clipboard. If the user deliberately presses and holds Ctrl... then presses C it will register.

procedure <anObject>.KeyUp(Sender: TObject; var Key: Word; Shift: TShiftState);
begin    
  if (ssCtrl in Shift) and (upcase(Char(key)) = 'C')
    then
      begin
        //Copy code    
      end;
end;

Is there a reason why this is happening?

Thanks!

like image 672
CodeSlinger512 Avatar asked Aug 12 '11 21:08

CodeSlinger512


3 Answers

It is not a sequence, it is a key combination. This means that Ctrl and C must be pressed at the same time. If the user doesn't do that, it can't be captured as Ctrl+C.

But I am guessing. I can't tell what the user is doing. Perhaps there is also a problem with the keyboard or the driver for it.


To account for what Rob said (accidently accepting other shift keys), change your code to:

if (Shift = [ssCtrl]) and (Upcase(Char(Key)) = 'C') then
like image 128
Rudy Velthuis Avatar answered Nov 17 '22 13:11

Rudy Velthuis


Ctrl+C is translated to a character message. So you better use a OnKeyPress handler (which is fired in response to a WM_CHAR):

procedure <anObject>.KeyPress(Sender: TObject; var Key: Char);
begin
  if Key = ^C then
    begin
      // Copy code
    end;
end;


update: I believe what's happening is this: when pressing quickly, the user is pressing 'Ctrl', then pressing 'C', then releasing 'Ctrl', lastly releasing 'C'. As you can see when the OnKeyUp for 'C' is fired the 'Ctrl' key is already released. You won't have this kind of problem with the translated message, if the OS registered the 'copy' key then OnKeyPress will be fired.

like image 35
Sertac Akyuz Avatar answered Nov 17 '22 15:11

Sertac Akyuz


Usually, OnKeyDown is more preferable then OnKeyup for such combo. Because users usually know to press those shift key before the char key but don't have a strict sense of which one to release first. Also, you can change the var Key to 0 to prevent the keys to be further interpreted by other levels of key events to override some default behaviour.

like image 33
Justmade Avatar answered Nov 17 '22 13:11

Justmade