RegisterHotKey implementation help

I would like to use RegisterHotKey to control the while loop below, without having to focus on the program. Pressing 1 toggles the bool mousetoggle, however I am not sure how to implement this with RegisterHotKey.

Below is the code in question. I would appreciate any advice or suggestions.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
	char key = ' ';
	while(key != VK_ESCAPE) // loop until user presses Escape
	{
		if(kbhit())
		{
			key = getch();
			switch(key)
			{
			case '1':
				mousetoggle = !mousetoggle; // invert bool var called mousetoggle
				break;
			}
		}
		if(mousetoggle) // when user presses '1', loop will enable
		{
			// code goes here
		}
	}
Last edited on
Because I see getch() there I suppose this is a console application? If yes, that won't work. RegisterHotKey() sends the WM_HOTKEY to a specific window or to the calling thread's message queue, and that requires that your program be a Windows GUI application, not a console application.

After that, the process is quite simple.
I was under the impression that RegisterHotKey are possible for console programs, because this example works fine.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <stdio.h>
#include <tchar.h>
#include <windows.h>

int main()
{       
	enum{ONE_KEYID = 1, TWO_KEYID = 2};
	RegisterHotKey(0, ONE_KEYID, MOD_NOREPEAT, 0x31); // register 1 key as hotkey
	RegisterHotKey(0, TWO_KEYID, MOD_NOREPEAT, 0x32); // register 2 key as hotkey
	MSG msg;
	while(GetMessage(&msg, 0, 0, 0))
	{
		PeekMessage(&msg, 0, 0, 0, 0x0001);
		switch(msg.message)
		{
		case WM_HOTKEY:
			if(msg.wParam == ONE_KEYID)
			{
				printf("1 Pressed");
			}
			else if(msg.wParam == TWO_KEYID)
			{
				printf("2 Pressed");
			}
		}
	}
	return 0;
}

Are you sure I must have a Windows GUI based program to use RegisterHotKey?
Last edited on
Your 2nd example is what webJose was describing.

RegisterHotKey is sending a WM_HOTKEY message. In your 2nd example, it works because you have a WinAPI message pump and handle the WM_HOTKEY message.

In your first post, you are not handling any messages (getch() does not check hotkeys) which is why it's not working.
Last edited on
I fixed my problem. I suggest anybody reading to use GetAsyncKeyState.

Thanks for the replies Disch and webJose.
Last edited on
Topic archived. No new replies allowed.