A problem when using GetKeyState()

Rer 80 Reputation points
2023-08-26T09:17:36.98+00:00

I wrote a function to catch long press but it only works outside the message loop. In my WinProc(), the message queue seems to be congested as the console keeps printing the character (in while loop #2) after I release the key. (It has detected the long press action indeed but GetKeyState() keeps telling me the key is down all the time in loop #2)

#define KeyPressed(nVirKey) (bool)(GetKeyState(nVirKey) & 0x8000)

int getLongPressed(char ch, clock_t DAS, clock_t ARR)
{
    cout << "Test for long press of " << ch << "..." << endl;
    cout << KeyPressed(ch) << endl;
    bool longPressed = false;
    clock_t clk = clock();
    while(KeyPressed(ch))
	{
        if((clock() - clk) > DAS)
		{
            longPressed = true;
			break;
		}
	}
	
	if(longPressed)
	{
		clk = clock();
		while(KeyPressed(ch))
		{
			if((clock() - clk) > ARR)
			{
				cout << ch << " ";
				clk = clock();
			}
		}
	}
    cout << endl << "End GetLongPressed()..." << endl;
    return longPressed;
}
Windows API - Win32
Windows API - Win32
A core set of Windows application programming interfaces (APIs) for desktop and server applications. Previously known as Win32 API.
2,678 questions
C++
C++
A high-level, general-purpose programming language, created as an extension of the C programming language, that has object-oriented, generic, and functional features in addition to facilities for low-level memory manipulation.
3,780 questions
{count} votes

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.