Link to home
Start Free TrialLog in
Avatar of fart_boy21
fart_boy21

asked on

GetAsyncKeyState consuming almost all CPU

Hi all,

I am currently using GetAsyncKeyState to launch an application. It works when the user presses a combination of keys, then creates the target application using CreateProcess. However, it seems that my PC is beginning to be sluggish since I had that app running. It loads from start up via the registry key

HKLM/Software/Microsoft/Current Version/Run (can't remember if the path is right, but you get what I mean)

The program is windowless and runs in a loop checking for the correct key combinations entered by the user.

A snippet of the code is as follows.

while(1)
{
....................................
if(GetAsyncKeyState(VK_CONTROL))             // Ctrl + Alt + G
                if(GetAsyncKeyState(VK_MENU))
                        if(GetAsyncKeyState('G'))
                                     launchApp();
....................................
}

In launchApp

launchApp()
{
        STARTUPINFO si;
        PROCESS_INFORMATION pi;

        ZeroMemory( &si, sizeof(si) );
        si.cb = sizeof(si);
        ZeroMemory( &pi, sizeof(pi) );

        CreateProcess( NULL, "pxapp.exe", NULL, NULL, 0, 0, NULL, NULL, &si, &pi );
}

I guess is that loop while(1) that is consuming all the resources, so it checks for key every few miliseconds, not elegant. Is there any way of optimising this program? Perhaps put it in idle state and trigger an event when received those key combinations. Will it help if I include a Sleep in the loop? Any ideas?

Thanx.
ASKER CERTIFIED SOLUTION
Avatar of mrwad99
mrwad99
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of fart_boy21
fart_boy21

ASKER

Oh. Thats what I thought. But then will it not miss some keystrokes since the app is "sleeping"?
Avatar of Mike Tomlinson
If your Sleep() interval is too long then, yes, you may miss a keystroke here and there.  You could probably go up to 50 though without losing anything...

An alternative would be to use a low level keyboard hook via WH_KEYBOARD_LL.
Ok thanks all for the answers. The Sleep really helped. I am just a beginner in Windows programming. I do not know the architechure of it.
Glad you got it sorted.