VC中的GetKeyState和GetAsyncKeyState的区别
0x8000是16进制数,用2进制表示为1000 0000 0000 0000, &是按位与
同样,如果键被按下,返回值最高位为1,则1xxx xxxx xxxx xxxx & 1000 0000 0000 0000得到的结果为1,否则为0,同样可以判断最高位的值。
需要说明的是,::GetKeyState()只能在键盘消息处理程序中使用,因为它只有在线程从消息队列中读取键盘消息时才会报告被查询键的状态,如果需要在键盘消息处理程序以外查询按键状态,则需要使用::GetAsyncKeyState来代替.
BOOL CAaDlg::PreTranslateMessage(MSG* pMsg)
{
// TODO: Add your specialized code here and/or call the base class
// TODO: Add your specialized code here and/or call the base class
//check ALT,SHIFT,CTRL presskey if is pressed!
if ((GetKeyState(VK_CONTROL)&0x8000)&&(pMsg->wParam=='G'))//pls didn't to use this method
MessageBox("ctrl+G");
if ((GetKeyState(VK_SHIFT)&0x8000))
MessageBox("VK_SHIFT");
// if ((GetKeyState(VK_MENU)&0x8000))
// MessageBox("VK_ALT");
if ((GetKeyState(VK_CONTROL)&0x8000)&&(GetKeyState(VK_MENU)&0x8000)&&(::GetAsyncKeyState ('T' )&0x8000))//this method is very good!(::GetAsyncKeyState('G'))
MessageBox("ctrl+ALT+T");
if ((GetKeyState(VK_MENU)&0x8000)&&(::GetAsyncKeyState (VK_ESCAPE )&0x8000))
MessageBox("ALT+ESC");
if ((GetKeyState(VK_CONTROL)&0x8000)&&(::GetAsyncKeyState (VK_ESCAPE )&0x8000))
MessageBox("CTRL+ESC");
if ((GetKeyState(VK_MENU)&0x8000)&&(::GetAsyncKeyState (VK_TAB)&0x8000))
MessageBox("ALT+TAB");
return CDialog::PreTranslateMessage(pMsg);
#include <windows.h>
int main(int argc, char* argv[])
{
long vk=0;
while(1)
{
vk=(::GetAsyncKeyState(VK_LSHIFT))&0x8000;
if(vk>1)
{
printf( "0x%x",vk);
MessageBox(0, "shift pressed", "infomation", MB_OK);
break;
}
}
return 0;
}