You can do this by sub-classing the control itself. This way, you get access to the WM_KEYUP messages it receives and thus, can see when it receives a VK_DELETE
First, you define a function to act as a window-proc for the control, next you subclass the control.
It's worth pointing out that your code steals focus from the control when you show a message-box displaying the item that was just selected. This means you click an item, a message-box is shown, you dismiss the box and hit delete, yet nothing happens. The fix is to either (0) Not show the message box, (1) manually (i.e in code) set the focus back to the control after the message box is dismissed or (2) click on an empty portion of the control before you hit the delete button.
Here's a very rough subclass function:
LRESULT CALLBACK myListBoxSubclassProc(HWND hWnd,
UINT uMsg,
WPARAM wParam,
LPARAM lParam,
UINT_PTR uIdSubclass,
DWORD_PTR dwRefData)
{
switch (uMsg)
{
case WM_KEYUP:
if (wParam == VK_DELETE)
{
int selectedIndex = SendMessage(hWnd, LB_GETCURSEL,0,0);
SendMessage(hWnd, LB_DELETESTRING, selectedIndex, 0);
MessageBeep(MB_OK);
}
break;
}
return DefSubclassProc(hWnd, uMsg, wParam, lParam);
}
And here's how you set the control to use it:
case WM_INITDIALOG:
hListBox = GetDlgItem(hDlg, IDC_LISTBOX);
hEditBox = GetDlgItem(hDlg, IDC_EDIT_MSG);
hAddButton = GetDlgItem(hDlg, IDC_ADDBUTTON);
SetWindowSubclass(hListBox, myListBoxSubclassProc, 0, 0);
return true;
You'll need to include <commctrl.h> and ensure that the following condition is met (before including it)
#if (_WIN32_WINNT >= 0x0501)