Windows API Single Key Hotkeys

GeekThis remains completely ad-free with zero trackers for your convenience and privacy. If you would like to support the site, please consider giving a small contribution at Buy Me a Coffee.

I have a love hate relationship with the Windows Documentation and with how MSDN is designed. I could spend hours trying to find the information I need and even then there will be information missing. To give you an idea of what I mean, I wanted to make a shortcut key that only requires a single key instead of having it use Shift, Ctrl, Windows Key or other modifiers.

In their documentation they don’t mention anywhere that modifiers are not required. From what the documentation shows, it appears that you must use one of the four available modifiers. I did a little bit of testing to see if I could make it so a modifier wouldn’t be required.

The basic syntax for creating a global shortcut hot key in Windows is as follows.

BOOL WINAPI RegisterHotKey(
	_In_opt_  HWND hWnd,
	_In_      int id,
	_In_      UINT fsModifiers,
	_In_      UINT vk
);

For the 3rd parameter, UINT fsModifiers you have a few options such as using MOD_ALT, MOD_CONTROL, MOD_WIN and some others. If you would like to see the full documentation on this function along with the options you can visit the MSDN Page.

What the documentation forgets to mention though, is if you leave fsModifiers as 0x00 or NULL no modifiers are used and your global shortcut key is registered. Below is an example showing this off this method using the hotkey of F8. Keep in mind that when a keyboard shortcut is registered, that key will not be able to perform it’s normal action. If you set the shortcut key to be a letter, the user won’t be able to type that letter in any other programs. Make sure you only define single keys that the user won’t normally press, such as the F1 - F12 keys.

#include <stdio.h>
#include <windows.h>

int main(int argc, char *argv[]) {
	if(!RegisterHotKey(NULL,1,0,VK_F8)) {
		printf("Failed to Register Hotkey - %lu\n",GetLastError());
		return -1;
	}

	MSG msg = {0};
	while(GetMessage(&msg,NULL,0,0) != 0) {
		if(msg.message == WM_HOTKEY) {
			printf("Hotkey Received\n");
		}
	}

	return 0;
}

And if you want the code I used to compile this using GCC, it’s gcc -Wall -o hotkey.exe hotkey.c.

Related Posts

C Get MP4 Duration

Function to get the duration of a MP4 file using C along with the MP4 container specification.

PHP - Check if Production or Sandbox

Use PHP to check of your site is on your development server or uploaded to the production server.

Setup PHP Development Web Server Quickly inside of Windows

Quickly setup a PHP development enviornment by using the built in PHP web server with no additional software required.

PHP Dynamic Subdomains

How to setup dynamic subdomains with PHP to give users a custom domain for their profile page.