您的位置:首页 > 其它

VC中的GetKeyState和GetAsyncKeyState的区别

2015-09-16 17:29 471 查看
VC中的GetKeyState和GetAsyncKeyState的区别

VC中添加组合快捷键时,经常会用到函数GetKeyState或函数GetAsyncKeyState,但是这两个函数有什么区别呢?各自都该如何使用呢.………………………………………………………………………………………………………………………………………………
使用::GetKeyState()返回一个short型的数,short型是16位有符号的数据类型,如果要查询的键被按下,返回值最高位被置1,则这个数表示负数,所以可以用<0或>0来判断。

0x8000是16进制数,用2进制表示为1000 0000 0000 0000, &是按位与

同样,如果键被按下,返回值最高位为1,则1xxx xxxx xxxx xxxx & 1000 0000 0000 0000得到的结果为1,否则为0,同样可以判断最高位的值。

需要说明的是,::GetKeyState()只能在键盘消息处理程序中使用,因为它只有在线程从消息队列中读取键盘消息时才会报告被查询键的状态,如果需要在键盘消息处理程序以外查询按键状态,则需要使用::GetAsyncKeyState来代替.
关于GetAsyncKeyState与GetKeyState二者最大区别:GetAsyncKeyState在按键不按的情况下为0,而GetKeyState在按键不按的情况下开始为0,当一次‘按下抬起’后变为1,依次循环。

MFC实例说明:

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);

}

WIN32实例说明:
#include "stdafx.h"

#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;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: