今天学习了最基本的MFC操作,键盘及键盘消息函数,跟着书中的内容自己编了个小程序。检测用户是否同时按下SHIFT和B键
第一步:先是建了一个单文档模式的MFC程序,添加了键盘消息及处理函数。键盘消息处理类CKeyboardDemoView,添加到CKeyboardView的项目中。然后再添加三个消息函数分别是WM_KEYDOWN,WM_KEYUP,WM_CHAR.系统自动为其分配了键盘消息的消息映射宏,和消息映射函数。
第二步:就是编写了实现的代码,先是在CKeyboardView的同文件中定义要用的函数,bShiftup,bShiftdown,bShiftB。全部是BOOL型,并且初始为FALSE。然后编写判断shift是否被按下的代码。
void CKeyboardDemoView::OnKeyDown(UINT nChar, UINT nRepCnt, UINT nFlags) { // TODO: Add your message handler code here and/or call default if(nChar==VK_SHIFT)//判断Shift键是否被按下 { //AfxMessageBox("dd"); bShiftdown=true; bShiftup=false; Invalidate(true);//显示信息 } CView::OnKeyDown(nChar, nRepCnt, nFlags); }
还有判断是否被松开
void CKeyboardDemoView::OnKeyUp(UINT nChar, UINT nRepCnt, UINT nFlags) { // TODO: Add your message handler code here and/or call default if(nChar==VK_SHIFT)//判断Shift键是否被释放 { //AfxMessageBox("dd"); bShiftup=true; Invalidate(true);//显示信息 bShiftdown=false; } CView::OnKeyUp(nChar, nRepCnt, nFlags); }
以及判断是否敲击了B键
void CKeyboardDemoView::OnChar(UINT nChar, UINT nRepCnt, UINT nFlags) { // TODO: Add your message handler code here and/or call default if((nChar==98)||(nChar==66))//判断是否敲击了字符键B键或b键 { if(bShiftdown) { bShiftB=true; bShiftdown=false; Invalidate(true);//显示信息 } } CView::OnChar(nChar, nRepCnt, nFlags); }
最后只要在Ondraw的函数中编写窗口输出函数
void CKeyboardDemoView::OnDraw(CDC* pDC) { CKeyboardDemoDoc* pDoc = GetDocument(); ASSERT_VALID(pDoc); // TODO: add draw code for native data here if(bShiftdown)//按下了Shift键 { pDC->TextOut(20,20,"用户按下了Shift键!"); } if(bShiftup)//释放了Shift键 { pDC->TextOut(20,20,"用户释放了Shift键!"); } if(bShiftB)//同时按下了Shift键和B键 { pDC->TextOut(20,20,"用户同时按下Shift键和B键!"); bShiftB=false; } }