[英]Polling the Keyboard in C and Win32 api
這段代碼沒有執行應做的事情。
當我按一下光標鍵時,菜單會跳轉多次。
我該如何解決這個問題?
。
相關源代碼
#include <windows.h>
#include <conio.h>
BOOL IsKeyPressed(KEY_CODE key)
{
if (GetAsyncKeyState(key) < 0)
{
return TRUE;
}
else
{
return FALSE;
}
}
int select_menu(char**menus, int x, int y, int items_count)
{
int selection = 0;
show_menu(x, y, menus, items_count);
gotoxy(x, y);
while (1)
{
if (IsKeyPressed(vk_Down))
{
int xx = wherex();
int yy = wherey() + 1;
if ((yy - x + 1) > items_count)
{
gotoxy(x, y);
}
else
{
gotoxy(xx, yy);
}
}
if (IsKeyPressed(vk_Up))
{
int xx = wherex();
int yy = wherey() - 1;
if (yy < y)
{
gotoxy(x, y + items_count);
}
else
{
gotoxy(xx, yy);
}
}
if (IsKeyPressed(vk_Return))
{
int xx = wherex();
int yy = wherey();
selection = yy - y + 1;
}
}
return selection;
}
參考:
您有一個軟件反彈。
從Microsoft頁面。 GetAsyncKeyState :
確定在調用函數時按鍵是向上還是向下,以及在上一次調用GetAsyncKeyState之后是否按下了該按鍵。
函數返回提供兩條信息:
1.密鑰的瞬時狀態。
2.密鑰的歷史狀態(自上次調用以來)。
您應該了解並同時使用兩者來做出決定。
為了防止反彈 ,請查看返回值的說明:
如果函數成功,則返回值指定自上次調用GetAsyncKeyState以來是否按下了該鍵,以及該鍵當前處於向上還是向下。 如果設置了最高有效位,則該鍵處於按下狀態 ;如果設置了最低有效位,則在上一次調用 GetAsyncKeyState 之后按下了該鍵 。 但是,您不應該依賴於此最后的行為。 有關更多信息,請參見備注。 [肺hp礦]
例如,您可以專門針對每種條件編寫函數:
BOOL IsKeyPressed(KEY_CODE key)
{
if(0x80000000 & GetAsyncKeyState(key))//most significant bit is high
return TRUE; //key IS down
else return FALSE;
}
BOOL WasKeyDown(KEY_CODE key)
{
if(0x00000001 & GetAsyncKeyState(key))//least significant bit is high
return TRUE; //key WAS down
else return FALSE;
}
如果某個時刻有必要在監視多個按鍵時同時查看歷史記錄和當前狀態,此示例說明了如何執行此操作。 特別是,此代碼定義了一組可用於終止應用程序的密鑰:
void KillThisApp(void)
{
if ((0x80000000 & GetAsyncKeyState(VK_CONTROL)) ||
(0x00000001 & GetAsyncKeyState(VK_CONTROL)))
{
if ((0x80000000 & GetAsyncKeyState('k')) ||
(0x00000001 & GetAsyncKeyState('k')) ||
(0x80000000 & GetAsyncKeyState('K')) ||
(0x00000001 & GetAsyncKeyState('K')) )
{
if((0x80000000 & GetAsyncKeyState(VK_SHIFT)) ||
(0x00000001 & GetAsyncKeyState(VK_SHIFT)))
{
gRunning = FALSE;
}
}
}
}
此版本不關心鍵是否已關閉,或者是下降,但很容易夠進行編輯,要求所有按鍵都下來了CAL的時間每次調用期間在高位只盯着。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.