We’ve already covered keyboard control with DelphiX, but you’re probably thinking, ‘Shouldn’t there be a way to do this without DelphiX?’. Well there is, and it’s pretty simple too.
Depending on what you’re wanting to do, we have two options. The first would be to use ASCII codes and the second would be to make use of Delphi’s VK_… command. The later of the two will not work in Kylix as it is specific to the Windows operating system. Still, let’s discuss both of these options.
ASCII
For every single key on the keyboard, including control keys, and also lower and uppercase letters, an ASCII code exists. We can use this fact to allow our program to check to see if a particular key has been pressed. Obviously we need to know the ASCII code for the key we’re looking to check for, but never fear for below you will find a list that shows just that. I’ve included most keys that you’ll need, and its decimal value.
This will have the effect of bringing up a window telling you the ASCII value of the key you just pressed. Simple.
Anyway, getting back to the task at hand, if you’ve been following the DelphiX tutorials you’ve already come across one of these ASCII codes in tutorial three on animation. There we used one of these codes to allow us to quit our application as soon as the user pressed Esc. The code for this looked like that shown below.
Here we used the FormKeyDown procedure which allowed us to take the ASCII code number of the Esc key (27), and close our program when the key is pressed. However if you recall, earlier I said that every key on the keyboard has an ASCII code. While this is true, in Delphi an OnKeyDown procedure will not distinguish between upper and lower case letters, instead always returning the number for the upper case letter. If you want to be able to tell the difference between a user pressing say a ‘A’ and an ‘a’ then you need to use the OnKeyPress event. The disadvantage of using an OnKeyPress event is that it cannot check to see if other keys are being pressed at the same time (such as the Shift or Ctrl key), and only one event is processed on every press of a key. Also, if we don’t use OnKeyPress, we can process both an OnKeyDown and OnKeyUp event so that we can make something different happen when the user lets go of the key.