Download src.zip - 1.5 KB
Download Keyboard.zip - 29.7 KB

Introduction
This projects demonstrates how one can delete different rows in a list at the same time. It also show how to use key press can initiate a function. I have used pretranslatemessage and accelerator keys to invoke the function required.
Using PreTranslateMessage to handle dialog keystrokes
Very often you hear questions from novice programmers asking how they can
trap keystrokes in a dialog based application. Presumably they tried to handle
WM_KEYDOWN/WM_KEYUP unsuccessfully. The whole problem is that in a dialog based
application the focus is always on one of the child controls and not on the main
dialog window. So what do you need to do? You need to override
PreTranslateMessage. I'll show you a simple example.
In the application I am using delete button of the keyboard to call OnBnClickedDelete()which will delete the selected items on the list control. The solution is so very easy and
straightforward with PreTranslateMessage as I'll demonstrate below.
BOOL CKeyboard1Dlg::PreTranslateMessage(MSG* pMsg)
{
if(pMsg->message==WM_KEYDOWN)
{
if(pMsg->wParam==(VK_DELETE))
OnBnClickedDelete();
}
if (m_hAcceleratorTable != NULL)
if (::TranslateAccelerator(m_hWnd, m_hAcceleratorTable, pMsg))
return TRUE;
return CDialog::PreTranslateMessage(pMsg);
}
All I have done is to check whether the message is a WM_KEYDOWN, and if it is
so, then I check to see if the wParam is VK_DELETE. If I find it so, OnBnClickedDelete()will be called.
Using Accelerator Keys
To add accelerators you first need to do the following steps
- Right click on the file name in the resource view and click on add resource.
- Add a new accelerator.
- An accelerator window will open. In the first column put the ID of the the function you want to call.
- Then chose the modifier that you want along with the key.
- The type VRITKEY is used when ctrl or alt etc is used with a key, if only key is used then used type ASCII.
- Finally add the code in the
PreTranslateMessage function.
if (m_hAcceleratorTable != NULL)
if (::TranslateAccelerator(m_hWnd, m_hAcceleratorTable, pMsg))
return TRUE;
Multiselection in a list
The following code is used to delete the multi selected items.
void CKeyboard1Dlg::OnBnClickedDelete()
{
for (int nItem = 0; nItem < m_MainList.GetItemCount(); )
{
if (m_MainList.GetItemState(nItem, LVIS_SELECTED) == LVIS_SELECTED)
m_MainList.DeleteItem(nItem);
else
++nItem;
}
}
Mainlist is the variable of the list control. LVIS_SELECTED is used to get the items which are selected.