Eric G
Eric G

Reputation: 3517

KeyDown KeyPress Conundrum - How to cancel the Space in Ctrl + Space

If I understand correctly, the KeyDown event cannot stop a character key (space) from being passed to a control.

But the KeyPress event doesn't tell me whether the Ctrl is down.

But I only need to cancel the space if the Ctrl is down.

How can I prevent an edit control from receiving the space keypress if the ctrl is also down?

Purpose: I have a text box, from which I am making search suggestions. I want to pop the suggestions up using the short cut ctrl+space. But in this case, I don't want to add the space to the edit text.

Upvotes: 2

Views: 1939

Answers (2)

Remy Lebeau
Remy Lebeau

Reputation: 596988

the KeyPress event doesn't tell me whether the Ctrl is down.

No, but you can use the Win32 GetKeyState() function instead.

How can I prevent an edit control from receiving the space keypress if the ctrl is also down?

Like this:

procedure TForm58.Edit1KeyPress(Sender: TObject; var Key: Char);
begin
  if (Key = ' ') and (GetKeyState(VK_CONTROL) < 0) then
  begin
    Key := #0;
    // do something...
  end;
end;

Upvotes: 6

David Heffernan
David Heffernan

Reputation: 613202

I have a text box, from which I am making search suggestions. I want to pop the suggestions up using the short cut ctrl+space. But in this case, I don't want to add the space to the edit text.

Handle the CTRL + SPACE input with a shortcut attached to an action, for instance. Handled that way the key will not reach the edit control.

Upvotes: 1

Related Questions