請檢查以下鏈接,解釋正確使用GetAsyncKeyState()和示例代碼。 http://www.mpgh.net/forum/31-c-c-programming/120656-proper-use-getasynckeystate.html
希望這個鏈接可以幫助你解決你的問題
編輯: 的GetAsyncKeyState()函數是不理想的你正在嘗試做的。
它所做的只是檢查鍵盤上某個鍵的實際當前位置。這樣做幾乎總是不正確的。
而是使用正確的輸入功能讀取控制檯輸入。請在下面找到示例代碼。
#include <stdio.h>
#include <windows.h>
int main()
{
DWORD mode; /* Preserved console mode */
INPUT_RECORD event; /* Input event */
BOOL done = FALSE; /* Program termination flag */
unsigned int counter = 0; /* The number of times 'Esc' is pressed */
/* Don't use binary for text files, OK? ;-) */
FILE* myfile = fopen("example.txt", "w");
/* Get the console input handle */
HANDLE hstdin = GetStdHandle(STD_INPUT_HANDLE);
/* Preserve the original console mode */
GetConsoleMode(hstdin, &mode);
/* Set to no line-buffering, no echo, no special-key-processing */
SetConsoleMode(hstdin, 0);
/* Give the user instructions */
printf(
"Press Escape as many times as you like.\n"
"Press anything else to quit.\n\n"
);
while (!done)
{
if (WaitForSingleObject(hstdin, 0) == WAIT_OBJECT_0) /* if kbhit */
{
DWORD count; /* ignored */
/* Get the input event */
ReadConsoleInput(hstdin, &event, 1, &count);
/* Only respond to key release events */
if ((event.EventType == KEY_EVENT)
&& !event.Event.KeyEvent.bKeyDown)
switch (event.Event.KeyEvent.wVirtualKeyCode)
{
case VK_ESCAPE:
counter++;
fprintf(myfile, "Escape: %d\n", counter);
printf("Button pressed!\n");
break;
default:
done = TRUE;
}
}
}
/* All done! */
printf("You pressed the Escape key %d times\n", counter);
fclose(myfile);
SetConsoleMode(hstdin, mode);
return 0;
}
你不能使用線性算法做到這一點......你需要爲你的程序添加一個監聽器。谷歌那。 –
使用鉤子。 「GetMessage」將一直處於空閒狀態,直到發生關鍵事件。對於比較髒的解決方案,在循環中添加一個「睡眠(10)」或其他東西。 – chris
在過去,我使用了'RegisterHotkey'和'UnregisterHotkey'的組合。我只想在窗口焦點時檢測按鍵,所以我在窗口不合焦的時候調用了'UnregisterHotkey',並在窗口返回焦點時將其註冊。也許這些功能會幫助你。如果在窗口沒有對焦的情況下未註銷熱鍵,則可能會弄亂其他應用程序熱鍵。 – Marlon