GetAsyncKeyState - How to check when key is released?

Hello guys.

I have this code:

1
2
3
4
5
while(1)
{
   if(GetAsyncKeyState(VK_F8) != 0)
      // PRESSED -> DO STUFF
}


I actually want my code to execute when the button is RELEASED, not when it's pressed.

How do I achieve this? I've searched around the internet and tried different methods such as this one:

1
2
3
4
5
6
7
8
9
10
11
12
while(1)
{
   if (GetAsyncKeyState(VK_F8) != 0)
   {
	while (GetKeyState(VK_F8) != 0)
        {

        }

	//RELESED -> DO STUFF
   }
}


But the latter doesn't work.

Will you help me out with this issue?

Thanks!
A potential solution is to try a nested if statement.

1
2
3
4
5
6
7
8
9
10
11
12
while(1)
{
   if (GetAsyncKeyState(VK_F8) != 0)
   {
	if(GetKeyState(VK_F8)==0) 
        {
                 //do stuff
        }
                //do nothing
	
   }
}


Although this should work it is important to not that this is unreliable for 2 reasons:
It doesn't work if the user clicks and release faster than your program takes for one loop.
It doesn't work if the user clicks, released and then clicks again faster than your program.

BUT, since on modern machines you can do this so fast that no human could really keep up, you can usually ignore both of these.
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
    bool f8_pressed = false;

    while(1)
    {
        if(GetAsyncKeyState(VK_F8) != 0)
            f8_pressed = true ;
        else if (f8_pressed)
        {
            f8_pressed = false;
            // do something on key release.
        }
    }
Topic archived. No new replies allowed.