argoneus
argoneus

Reputation: 1147

How to associate an item from a combobox with a Win32 API hotkey?

I have a combobox with items - hotkeys. I want to associate each one to a Win32 hotkey, e.g. F2 to VK_F2 and then call that one with RegisterHotkey. What's the best way to do this? I looked up stuff and perhaps hexadecimal values could help, but it doesn't say how to use them. Thanks.

I'm sorry I couldn't provide more information but I don't know what else should I include :/

Upvotes: 0

Views: 427

Answers (1)

Ken White
Ken White

Reputation: 125728

You can use TextToShortCut, and then decode the returned TShortCut into the required values for RegisterHotKey:

var
  Shortcut: TShortCut;
  Flags: Cardinal;
  Key  : Word;
  Shift : TShiftState;
begin
  ShortCut := TextToShortCut(ComboBox1.Items[ComboBox1.ItemIndex]);
  Flags := 0;
  Key   := 0;
  Shift  := [];
  ShortCutToKey(Shortcut, Key, Shift);
  if ssCtrl in Shift then
    Flags := Flags or MOD_CONTROL;
  if ssShift in Shift then
    Flags := Flags or MOD_SHIFT;
  if ssAlt in Shift then
    Flags := Flags or MOD_ALT;

  // You should check the return value of RegisterHotKey - it returns
  // a BOOL indicating success or failure. Omitted because your 
  // question isn't about using RegisterHotKey.
  RegisterHotKey(Application.Handle, YourHotKeyID, Flags, Key );
end;

TextToShortCut and ShortCutToKey are both defined in the Menus unit.

YourHotKeyID is a value between $0000-$BFFF you define that will be passed to your app in the wParam when you receive the WM_HOTKEY message.

With all that being said, you should reconsider your choice of UI controls. If you use a THotKey, the user can just press the key combination they want to use (instead of scrolling through a list). You can then use the THotKey.HotKey in place of the ShortCut variable in the sample code (you can pass it directly to ShortCutToKey, and eliminate the ShortCut variable entirely):

ShortCutToKey(HotKey1.HotKey, Key, Shift);
// ... remainder of code

And, in anticipation of your soon-to-come comment :), how to catch and handle the WM_HOTKEY message and how to handle multiple hotkeys you have registered should be a new question. This one was specifically about a combobox and a hotkey; how to handle the hotkey being pressed is totally different.

Upvotes: 1

Related Questions