Search code examples
delphidelphi-xe4

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.


Solution

  • 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;