Click here to Skip to main content
Click here to Skip to main content

Global hotkeys made easy

By , 19 Oct 2003
 

Introduction

This article will show you how to use the CHotkeyHandler class in order to manage and create global hotkeys.

Using the code

#include <conio.h>
#include <stdio.h>
#include "hotkeyhandler.h"

void handA(void *)
{
  printf("this is A\n");
}

void handQ(void *)
{
  printf("this is Q\n");
}

void hand1(void *param)
{
  WinExec((char *)param, SW_SHOW);
}

int main(void)
{
  int err, id;

  CHotkeyHandler hk;

  hk.InsertHandler(MOD_CONTROL | MOD_ALT, 'Q', handQ, id);
  hk.InsertHandler(MOD_CONTROL | MOD_ALT, 'A', handA, id);
  hk.InsertHandler(MOD_CONTROL | MOD_ALT, '1', hand1, id);

  err = hk.Start("calc.exe");
  if (err != CHotkeyHandler::hkheOk)
  {
    printf("Error %d on Start()\n", err);
    return err;
  }
  printf("hotkeys started!!!\n...press any key to stop them...\n");
  getch();
  err = hk.Stop();
  return 0;
}

First we declare a CHotkeyHandler instance. We then start inserting the hotkeys defined by their Control key, Virtual Key, Callback function. The InsertHandler() will return us an identifier for the registered hotkey. You can use this id with the RemoveHandler(). After we have inserted our handlers you can enable the hotkeys by calling Start(). You should always check for error codes returned by the CHotkeyHandler methods. The Start() will take an optional parameter that will be passed to the registered callback when it gets invoked. We then disable all hotkeys via Stop()

For more information about error codes and other methods description please refer to the CHotkeyHandler.cpp file. That's all.

History

  • 9 May 2003
    • Initial CodeProject version
  • 20 Oct 2003
    • Source code updated

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

Elias Bachaalany
Web Developer
United States United States
Member
Elias (aka lallousx86, @0xeb) has always been interested in the making of things and their inner workings.
 
His computer interests include system programming, reverse engineering, writing libraries, tutorials and articles.
 
In his free time, and apart from researching, his favorite reading topics include: dreams, metaphysics, philosophy, psychology and any other human/mystical science.
 
Former employee of Hex-Rays (the creators of IDA Pro), was responsible about many debugger plugins, IDAPython project ownership and what not.
 
Elias currently works at Microsoft as a software security engineer.
 
More articles and blog posts can be found here:
 
- http://lallousx86.wordpress.com/
- http://0xeb.wordpress.com/
- http://www.hexblog.com/?author=3

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralProblem while compiling in VC++ 2008memberNitsanBr30 Aug '08 - 12:41 
I tried running the snippet shown with the project -
I added a main function to the VS project and I'm having compilation errors.
 
This is the log:
1>------ Build started: Project: globalhotkeys, Configuration: Debug Win32 ------
1>Compiling...
1>maintest.cpp
1>c:\users\myuser\desktop\globalhks\maintest.cpp(40) : warning C4996: 'getch': The POSIX name for this item is deprecated. Instead, use the ISO C++ conformant name: _getch. See online help for details.
1> d:\program files (x86)\microsoft visual studio 9.0\vc\include\conio.h(145) : see declaration of 'getch'
1>Linking...
1>maintest.obj : error LNK2005: "void __cdecl handA(void *)" (?handA@@YAXPAX@Z) already defined in globalhotkeys.obj
1>maintest.obj : error LNK2005: "void __cdecl handQ(void *)" (?handQ@@YAXPAX@Z) already defined in globalhotkeys.obj
1>maintest.obj : error LNK2005: "void __cdecl hand1(void *)" (?hand1@@YAXPAX@Z) already defined in globalhotkeys.obj
1>maintest.obj : error LNK2005: _main already defined in globalhotkeys.obj
1>.\Debug/globalhotkeys.exe : fatal error LNK1169: one or more multiply defined symbols found
1>Build log was saved at "file://c:\Users\Nitsan\Desktop\globalhks\Debug\BuildLog.htm"
1>globalhotkeys - 5 error(s), 1 warning(s)
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
 
I'm pretty new to C++ and do not understand what exactly should I do with those problems.
maintest - the cpp file containing the snippet in the article.
 
Thanks
GeneralRe: Problem while compiling in VC++ 2008member428814 Aug '09 - 10:38 
The project has already a main function
 
---

GeneralErrors and problemsmemberVal Samko18 Oct '03 - 11:26 
1. In int CHotkeyHandler::RemoveHandler(const int index)
replace `if (m_listHk.size() < index)`
with `if (m_listHk.size() <= index)`,
otherwise your `index out of range` check is wrong.
 
2. I did not find where you actually delete elements
from tHotkeyList. Do you? Otherwise it's a potential
memory leak, i.e. if we add/delete hotkeys, memory
does not get deallocated.
 
3. Please remove `using std::vector;` from the header file,
it may screw the users code after #include "HotkeyHandler.h",
if user has a non STD implementation of vector.
using ANYTHING; in the global scope is always bad.
GeneralRe: Errors and problemsmemberlallous20 Oct '03 - 1:48 
1. fixed
2. Currently, I don't delete but I recycle. every deleted item is marked as deleted and when you insert a new element it will take its place.
3. fixed
Generallocal hotkeymembershahrzad4 Aug '03 - 1:00 
Can we define local hotkeys in an application only?
GeneralRe: local hotkeysussAnonymous9 Aug '03 - 11:01 
Hi,
 
I cannot think of something optimal at the moment, but here is what comes to mind at first:
 
---
create a thread that will keep calling GetKeyState() and checking whether the desired key combination is made. If so then signal to your main thread to take action.
---
 
hope that helps,
lallous
GeneralHotkeys Vs. KB Hooksmembersumudu12 Jun '03 - 6:41 
I've been using global hotkeys (with MFC) for a while.
 
Recently, I found out that what I was doing with the hotkeys can be done using a keyboard hook as well. I don't know much about hooks. So, I was wonder if anybody could help me by listing the pros and cons of the two methods as opposed to each other
 
Much appreciated.
Big Grin | :-D
GeneralRe: Hotkeys Vs. KB Hooksmemberlallous18 Jun '03 - 3:04 
Hi,
 
Keyboard hooks are useful and much powerful, however global hotkeys can serve your simple needs.
 
Hook:
.mostly need a additional dll where the hook code will reside
.mostly need to get itself attached to every running process thus adding possibility to slow down the system
.are powerful and can be triggered even from inside games
.can be used as filters (you can decide whether to passdown a key or not)
 
Global hotkeys:
.sometimes they are not triggered from inside games
.they are light and for one purpose (get triggered on hotkey)
 
Hope that helps,
Elias
GeneralRe: Hotkeys Vs. KB Hooksmembersumudu18 Jun '03 - 6:42 
Thanks,
Just the kindda answer I was looking for.
Rose | [Rose]
GeneralRe: Hotkeys Vs. KB HooksmemberJGHG24 Jun '04 - 2:04 
Then how do we do hooks?
 
I tried this code snippet, it compiled and everything but failed with error code 4 (could not register key??)
I removed all but '1', and then it would compile but when I press 1 anywhere nothing happens, pressing 1 within the console program ends it.

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web02 | 2.6.130523.1 | Last Updated 20 Oct 2003
Article Copyright 2003 by Elias Bachaalany
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid