Key Presses?

closed account (967L1hU5)
How can I make it so the user doesn't have to press enter when entering something on a console program? Like for example, the program says "Press Q to quit", the user only has to press "Q", and not "Q" than ENTER? I read something about it before, but I didn't pay much attention to it before. Could someone explain how to do it or post a reference that explains it?
I don't think there's a way to do this with standard C++, but there are various methods to get keypresses - on windows you could use the WinAPI:

1
2
3
4
5
6
7
8
9
10
11
#include <iostream>
#include <windows.h>

int main()
{
std::cout<<"Press Q to exit"<<std::endl;
while(!(GetASyncKeyState(VK_Q)>0));
return 0;
}
/*not 100% sure if it was like that, has been a while since I last used the WinAPI
 and I don't have access to windows right now*/


http://msdn.microsoft.com/en-us/library/windows/apps/ms646293%28v=vs.85%29.aspx
Last edited on
closed account (967L1hU5)
When I compile, I get two errors:
error: 'GetASyncKeyState' was not declared in this scope
error: 'VK_Q' was not declared in this scope
Try adding <winuser.h> - though technically it should be included by windows.h if I'm not mistaken.
closed account (967L1hU5)
Already tried that from
http://msdn.microsoft.com/en-us/library/windows/apps/ms646293%28v=vs.85%29.aspx

Got the same result.
Well, that's strange- what OS/compiler are you using?
closed account (967L1hU5)
Windows 7 Ultimate x86, with Codeblocks. GNU GCC Compiler.
Last edited on
MinGW or Cygwin?
closed account (967L1hU5)
MinGW.
Does
 
MessageBox(NULL, "Hello World!", "Test",  MB_OK);


work?
closed account (967L1hU5)
Yeah.

P.S. That's some nifty code!
Ok, now I'm confused. If that works, GetASyncKeyState should too.
closed account (967L1hU5)
Any ideas on what it might be?
It's Async.
Using that function isn't all that much of a good idea, since it registers key presses even outside the window.
That's not the expected behavior and some antivirus software doesn't like programs that use the function either.
(and without a "Sleep" it would burn all CPU time it can get until someone finally hits a key)

_getch should do the trick:
http://msdn.microsoft.com/de-de/library/078sfkak%28v=vs.80%29.aspx
Async. Of course. I remember making that typo all the time in the past too.

I never said it was good code, I just said it was a conceivable way to do it. But yeah, I suppose _getch is better for the purposes of the OP.


doesn't explain why VK_Q isn't recognized though
Last edited on
closed account (967L1hU5)
Thanks!
Topic archived. No new replies allowed.