MFC初探 —— 捕获键盘消息

方式一:重载PreTranslateMessage()

        在类向导的虚函数中增加PreTranslateMessage()

        注意:如果处理WM_KEYDOWN消息,按键在按下不抬起的情况下,每隔一段时间就会触发一次,如果只想要触发一次,请使用WM_KEYUP

BOOL CTest::PreTranslateMessage(MSG* pMsg)
{
	// TODO: 在此添加专用代码和/或调用基类
	if (pMsg->message == WM_KEYUP)
	{
		switch (pMsg->wParam)
		{
		case VK_UP:
			printf("WM_KEYUP UP\n"); break;
		case VK_DOWN:
			printf("WM_KEYUP DOWN\n"); break;
		case VK_LEFT:
			printf("WM_KEYUP LEFT\n"); break;
		case VK_RIGHT:
			printf("WM_KEYUP RIGHT\n"); break;
		case VK_PRIOR:
			printf("WM_KEYUP PgUp\n"); break;
		case VK_NEXT:
			printf("WM_KEYUP PgDn\n"); break;
		default:
			break;
		}
	}
	if (pMsg->message == WM_KEYDOWN)
	{
		switch (pMsg->wParam)
		{
		case VK_UP:
			printf("WM_KEYDOWN UP\n"); break;
		case VK_DOWN:
			printf("WM_KEYDOWN DOWN\n"); break;
		case VK_LEFT:
			printf("WM_KEYDOWN LEFT\n"); break;
		case VK_RIGHT:
			printf("WM_KEYDOWN RIGHT\n"); break;
		case VK_PRIOR:
			printf("WM_KEYDOWN PgUp\n"); break;
		case VK_NEXT:
			printf("WM_KEYDOWN PgDn\n"); break;
		default:
			break;
		}
	}
	return CDialogEx::PreTranslateMessage(pMsg);
}

方式二:注册热键 + 重载OnHotKey()

1、在OnInitDialog()函数中增加代码块

BOOL CTest::OnInitDialog()
{   
    ...
    ...

    // TODO: 在此添加额外的初始化代码
	RegisterHotKey(m_hWnd, 1, NULL, VK_UP);
	RegisterHotKey(m_hWnd, 2, NULL, VK_DOWN);
	RegisterHotKey(m_hWnd, 3, NULL, VK_LEFT);
	RegisterHotKey(m_hWnd, 4, NULL, VK_RIGHT);
	RegisterHotKey(m_hWnd, 5, NULL, VK_PRIOR);
	RegisterHotKey(m_hWnd, 6, NULL, VK_NEXT);
	return TRUE;  // 除非将焦点设置到控件,否则返回 TRUE
}

2、在类向导中增加消息OnHotKey()

void CKeyboardDlg::OnHotKey(UINT nHotKeyId, UINT nKey1, UINT nKey2)
{
	// TODO: 在此添加消息处理程序代码和/或调用默认值
	switch (nHotKeyId)
	{
	case 1:
		PostMessage(WM_COMMAND, MAKEWPARAM(IDC_BUTTON_UP, BN_CLICKED), NULL);
		break;
	case 2:
		PostMessage(WM_COMMAND, MAKEWPARAM(IDC_BUTTON4_DOWN, BN_CLICKED), NULL);
		break;
	case 3:
		PostMessage(WM_COMMAND, MAKEWPARAM(IDC_BUTTON_LEFT, BN_CLICKED), NULL);
		break;
	case 4:
		PostMessage(WM_COMMAND, MAKEWPARAM(IDC_BUTTON_RIGHT, BN_CLICKED), NULL);
		break;
	case 5:
		PostMessage(WM_COMMAND, MAKEWPARAM(IDC_BUTTON_PgUp, BN_CLICKED), NULL);
		break;
	case 6:
		PostMessage(WM_COMMAND, MAKEWPARAM(IDC_BUTTON8_PgDn, BN_CLICKED), NULL);
		break;

	default:
		break;
	}
	CDialogEx::OnHotKey(nHotKeyId, nKey1, nKey2);
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值