Problem with OnKeyDown in Delphi

2019-07-13 11:26发布

I am working with Delphi. I want to track on which key is pressed. I am using KeyDown event of TForm. It is working fine but the problem is that, if I press and lower case letter, though it gives me upper case of that letter. How can I recognize the key pressed is lower case or upper case?

1条回答
Luminary・发光体
2楼-- · 2019-07-13 12:02

If you want to track alphanumerical keys, then you should use KeyPress. Try this:

procedure TForm1.FormKeyPress(Sender: TObject; var Key: Char);
begin
  ShowMessage(Key);
end;

The problem with KeyDown is that is responds to a key being depressed, and surely enough, if you want to enter either "K" or "k" on the keyboard, you press the same button, right? So if you want to stick to KeyDown, then you need to check separately if the Caps Lock key is on, or if the Shift key is depressed. To test if a toggle key (such as Caps Lock) is on, or if a regular key is depressed, you can use

function IsKeyDown(const VK: integer): boolean;
begin
  IsKeyDown := GetKeyState(VK) and $8000 <> 0;
end;

function IsKeyOn(const VK: Integer): boolean;
begin
  IsKeyOn := GetKeyState(VK) and 1 = 1;
end;

To check if the Caps Lock key is on, use IsKeyOn(VK_CAPITAL). To check if the shift key is depressed, use IsKeyDown(VK_SHIFT).

An alternative way of checking if the shift key is depressed, which only works in the OnKeyDown event handler, is to check if ssShift in Shift, where Shift is a parameter of that event handler function.

(By the way, because the action of Caps Lock being on is counteracted by the Shift key (that is, if you press Shift+A when Caps Lock is on, a small "a" is inserted), the check to employ when testing for capitals is

IsKeyOn(VK_CAPITAL) xor IsKeyDown(VK_SHIFT)

using the xor operator.)

查看更多
登录 后发表回答