views:

413

answers:

1

I've got a quaint little app that pops up an on screen numberpad/calculator written in Delphi. I'd like to make it so if you pressed 'enter' (on the number pad) you'd be pressing '=' and if you pressed 'return' (on the main keyboard) you'd be pressing 'OK'.

There's an OK button who is the form's default guy which responds to hitting enter or return. There is also an onkeydown event handler which potentially might capture both Enter and return as vk_return. But its duties are usurped by the default 'OK' button.

If I could know the difference between return and enter, then I could get rid of my default property on the OK button and just do hit the OK button's click event handler on the form key down function, but alas they are both VK_RETURN.

+13  A: 

Override the WM_KEYDOWN message handler:

  procedure WMKeyDown(var Message: TWMKeyDown); message WM_KEYDOWN;

Implement it so that it calls the ancestor for anything but what you're interested in. You can detect the difference between the return key and the enter key by the "extended" bit in the key data message field:

procedure TForm1.WMKeyDown(var Message: TWMKeyDown);
const
  // Message.KeyData format:
  // [0..15 repCount][16..23 scan code][24 extended bit][25..28 reserved]
  // [29 context][30 previous state][31 transition state]
  KD_IS_EXTENDED = 1 shl 24;
begin
  if Message.CharCode <> VK_RETURN then
  begin
    inherited;
    Exit;
  end;
  if (KD_IS_EXTENDED and Message.KeyData) <> 0 then
    ShowMessage('Keypad Enter')
  else
    ShowMessage('Return');
end;
Barry Kelly