用VC编写一个指法练习的小程序,如图所示。
大致功能是:
启动则随即显示一行字母,然后敲击键盘,击键代码与光标指针“ ^ ”对应字母相同,则消去字母行中该字母,否则保留。
这个程序别的都好说,主要的问题是对WM_CHAR消息的响应问题。
为了截获键盘击键的值,需要用到WM_CHAR消息。但在Project中添加该消息后会发现,程序无法响应该消息。即击键后程序并没有执行到该消息对应的函数处。参考MSDN对该消息的描述:
This member function is called by the framework to allow your application to handle a Windows message. The parameters passed to your function reflect the parameters received by the framework when the message was received. If you call the base-class implementation of this function, that implementation will use the parameters originally passed with the message and not the parameters you supply to the function.
关键的意思是要执行WM_CHAR消息,程序焦点必须在主窗口上。但不幸的是,程序运行以后,焦点在按钮上。解决的方式是使用PreTranslateMessage消息,进行处理,将焦点设置到主窗口上。具体代码如下:
BOOL CTTDlg::PreTranslateMessage(MSG* pMsg)
{
// TODO: Add your specialized code here and/or call the base class
if ( pMsg->message == WM_KEYDOWN ||pMsg->message == WM_CHAR)
{
{
pMsg->hwnd = m_hWnd;
return FALSE;
}
}
return CDialog::PreTranslateMessage(pMsg);
}
此后即可响应WM_CHAR消息了。
上面文字,关键是学习设置应用程序焦点的方法!
源代码: