VC中至少有三种快捷键编程的方法,通常在SDI,MDI结构的程序中通过加入Acclelerator资源的消息响应,快速地实现快捷键功能;
除些之内,还有另两种方法.通常用在基于对话框的程序中.
1.
- #define IsCTRLpressed() ((GetKeyState(VK_CONTROL) & (1<<(sizeof(SHORT)*8-1)))!= 0) //判断Ctrl键是否按下.
- BOOL CTDlg::PreTranslateMessage(MSG* pMsg)
- {
- if(pMsg->message == WM_KEYDOWN)
- {
- if(IsCTRLpressed())
- {
- switch(pMsg->wParam)
- {
- case 'A':
- AfxMessageBox("you press ctrl + a");
- break;
- case 'B':
- AfxMessageBox("you press ctrl + b");
- break;
- }
- }
- }
- return CDialog::PreTranslateMessage(pMsg);
- }
.2.先添加Accelerator资源,比如:IDR_ACCELERATOR1,在其中添加要使用的快捷键资源:如
ID:IDR_CTRLTEST
Key:Ctrl + K
Type:VIRTKEY
- HACCEL m_hAcc;
- BOOL CTDlg::OnInitDialog()
- {
- ....
- m_hAcc = LoadAccelerators(AfxGetApp()->m_hInstance, MAKEINTRESOURCE(IDR_ACCELERATOR1));
- }
- BOOL CTDlg::PreTranslateMessage(MSG* pMsg)
- {
- int iRet;
- switch(pMsg->message)
- {
- case WM_KEYDOWN:
- case WM_SYSKEYDOWN:
- iRet = TranslateAccelerator(m_hWnd, hAcc, pMsg);
- if(iRet)
- {
- return TRUE;
- }
- }
- return CDialog::PreTranslateMessage(pMsg);
- }
- 然后手工添加快捷资源的消息响应:
- 比如:
-
- afx_msg void OnTest();
-
- DECLARE_MESSAGE_MAP()
- BEGIN_MESSAGE_MAP(CTDlg, CDialog)
- ON_COMMAND(IDR_CTRLTEST, OnTest)
- END_MESSAGE_MAP()
- void CTDlg::OnTest()
- {
- AfxMessageBox("you press ctrl + k");
- }
发表于 @ 2008年08月03日 22:14:00|评论(loading...)|收藏