Recent

Author Topic: How to capture keypress inside the whole Form  (Read 12659 times)

flasher86

  • New Member
  • *
  • Posts: 15
How to capture keypress inside the whole Form
« on: November 25, 2010, 01:03:43 pm »
hi, I am writing an app which can be controlled all by the keyboard, but with graphical user interface. I have a lot of groupboxes and other controls on the main form.

How to capture keypress globally in my form, no matter which control is focused? I don't want to link every control on my form with it. I know there is a global hook (for the whole system) but then some Antivirus programs may detect it as a threat.

typo

  • Hero Member
  • *****
  • Posts: 3051
Re: How to capture keypress inside the whole Form
« Reply #1 on: November 25, 2010, 01:17:07 pm »
Set KeyPreview form property to True and handle key events on form event handlers.

TurboRascal

  • Hero Member
  • *****
  • Posts: 672
  • "Good sysadmin. Bad programmer."™
Re: How to capture keypress inside the whole Form
« Reply #2 on: November 25, 2010, 06:39:10 pm »
It's easiest to enable it when the form is created (OnCreate event):

Code: Pascal  [Select][+][-]
  1. procedure TForm1.FormCreate(Sender: TObject);
  2. begin
  3.   Form1.KeyPreview := True  // this enables the form to receive keypress events
  4. end;
  5.  

Then you handle the keypresses. If you need to capture keys with printing characters, you can use the OnKeyPress event, but for capturing special keys (like F-keys etc.) you need to use OnKeyDown event, but you may also need to handle OnKeyUp event afterwards (depending on what you do), like this:

Code: Pascal  [Select][+][-]
  1. procedure TForm1.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState  );
  2. begin
  3.   //your keypress handler goes here
  4. end;
  5.  
  6. procedure TForm1.FormKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState);
  7. begin
  8.   //your key RELEASE handler goes here; it may be necessary if using modifier keys
  9. end;
  10.  
Regards, ArNy the Turbo Rascal
-
"The secret is to give them what they need, not what they want." - Scotty, STTNG:Relics

 

TinyPortal © 2005-2018