Hey, Im making a program in C++ that detects what the user types before pressing enter. So it uses GetAsyncKeyState in the following way:

#include <iostream>
#include <fstream>
#include <windows.h>

using namespace std;

int main() {
SetCurrentDirectory("C:\\");
ofstream log;
char loop;
string input;

loop = 'a';
while(loop = 'a') {
if(GetAsyncKeyState(VK_0x41)) {
cout << "a" << endl;
input+="a";
Sleep(1000);
}

//Rest of GetAsyncKeyState alphabet and some other commands

if(input == "hello") {
cout << "You successfully entered hello" << endl;
Sleep(1000);
getch();
return 0;
}

So its a basic program and it would have the rest of the GetAsyncKeyState alphabet and a couple other buttons, and it works fine. But if I don't add the Sleep(1000); to sleep for 1 sec between getting sync key states, it infiniately prints (outputs) the letter I entered. So if I say Sleep(80) it prints the letter I entered 2 times. Sleep(60), 4 times etc.

So its annoying cause it takes forever to type and misses a couple keys I press with the Sleep functions in between. But without them, it will keep printing out the sync key state key. It won't stop.

Is there any way or any other command I can use that does the same thing, but keeps up with printing keys as I type, and doesn't keep on printing out keys infinately at a very high speed, until I close the program? Even with the cout << "You sucessfully entered hello!" <<endl; command, it keeps printing out that line over and over....

Please help!

Thanks in advance,
Aidan.

There's not much you can do about it, i've hit this problem myself when scripting in AutoHotkey. One thing you have to know is that the input detection speed is highly dependant on that particular machine's capabilities and extremely sensitive to system loads. Your computer needs Sleep(1000), a faster one may only need Sleep(300) while old machines will probably need 3000 and up. When you're only coding for your own computer it's okay, but when you need other people to use your software you'll run into a lot of trouble.

There has to be another way, however don't ask me as i don't know. I'm just pointing out what i encountered myself - your current approach will not work.

You'll probably find Reading Input Buffer Events useful.

I see what that does, but the code on that page is more advanced than what I know how to do currently... I will research this more though. Im guessing what it does is it kinda filters input... Ill figure it out, thanks!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.