//#define StartThread(thrFun) CloseHandle(CreateThread(NULL,0,thrFun,NULL,0,NULL))
DWORD WINAPI Thread_listen_key(void *arg)
{
OutputDebugString("start listenning the keyboard....\n");
//监听以下按键值的触发
CONST UCHAR keyMap[] = { VK_UP,VK_DOWN,VK_LEFT,VK_RIGHT,VK_DELETE,VK_END,VK_NEXT,VK_INSERT,VK_HOME,VK_PRIOR };
uint32_t value = 0;
int nKeyPressed = 0;
int keyLen = sizeof(keyMap);
while (true)
{
nKeyPressed = 0;
value = 0;
//if (GetKeyState(VK_CONTROL)){}
for (size_t i = 0; i < keyLen; i++)
{
if (GetAsyncKeyState(keyMap[i]))
{
nKeyPressed++;
value |= 1 << i;
}
}
if (nKeyPressed > 0)
{
//to do your key event logic here...
printf("Value=%04X.CNT[%d]\n",value,nKeyPressed );
OutputDebugString("some key down.");
}
Sleep(200);
}
return 0;
}
typedef struct TAG_KEY_INFO
{
uint8_t key_curr;
uint8_t key_old;
uint8_t long_cnt;
uint8_t flag_pressed;
uint8_t flag_long_dn;
} KeyInfo;
typedef enum ENUM_KEY_ID
{
vk_up,
vk_down,
vk_left,
vk_right,
vk_delete,
vk_end,
vk_next,
vk_insert,
vk_home,
max_touch_key
};
KeyInfo g_key_info[max_touch_key];
void clear_key_flags(int key_id)
{
if (key_id < 0 || key_id >= max_touch_key)
{
for (size_t i = 0; i < max_touch_key; i++)
{
g_key_info[i].flag_pressed = 0;
}
return;
}
g_key_info[key_id].flag_pressed = 0;
}
DWORD WINAPI Thread_listen_key(void* arg)
{
CString str;
str.Format(_T("Start specified key listenning...\n"));
OutputDebugString(str);
//监听以下按键值的触发,windows自带虚拟键值,位置顺序要和ENUM_KEY_ID一致才行
CONST UCHAR g_key_index_code[] = { VK_UP,VK_DOWN,VK_LEFT,VK_RIGHT,VK_DELETE,VK_END,VK_NEXT,VK_INSERT,VK_HOME,VK_PRIOR };
uint32_t key_flags = 0;
int key_len = sizeof(g_key_index_code);
int cnt = 0;
while (true)
{
key_flags = 0; //PC端获取键值形成32bits的标志位
for (int i = 0; i < key_len; i++)
{
if (GetAsyncKeyState(g_key_index_code[i]))
{
key_flags |= 1 << i;
}
}
for (size_t i = 0; i < max_touch_key; i++)
{
if (key_flags & (1 << i))
{
g_key_info[i].key_curr = 1;
g_key_info[i].long_cnt++;
if (g_key_info[i].key_old == 0)
g_key_info[i].flag_pressed = 1;
if (g_key_info[i].long_cnt > (10 * 3))
{ // N second
g_key_info[i].long_cnt = 0x00;
if (g_key_info[i].flag_pressed == 0)
{
g_key_info[i].flag_long_dn = 1;
}
}
}
else
{
g_key_info[i].key_curr = 0;
g_key_info[i].long_cnt = 0;
g_key_info[i].flag_long_dn = 0; // clear long press when button release!
}
g_key_info[i].key_old = g_key_info[i].key_curr;
}//<< end for
Sleep(100);
//todo your key logic...
if (g_key_info[vk_home].flag_pressed)
{
str.Format(_T("RawData=%06X , HomeKey pressed.\n"), key_flags);
OutputDebugString(str);
}
if (g_key_info[vk_end].flag_pressed)
{
str.Format(_T("RawData=%06X , EndKey pressed.\n"), key_flags);
OutputDebugString(str);
}
//clear all key flags
clear_key_flags(-1);
}
return 0;
}