I have a business requirement that for message boxes, the user cannot press the enter key to accept the default option, but has to press the key of the option. eg. Given a MessageBox with the options Yes/No, the user must press the Y or N keys. Now I've implemented this below using keyboard hooks, but when the code returns, the KeyUp event also gets returned to the calling code as well.
So the question is: How do I flush all the keyboard events before returning to the calling code?
I've removed boiler plate code, but if you need it, please advise.
The calling code:
private static ResultMsgBox MsgResultBaseNoEnter(string msg, string caption, uint options)
{
ResultMsgBox res;
_hookID = SetHook(_proc);
try
{
res = MessageBox(GetForegroundWindow(), msg, caption, options);
}
finally
{
UnhookWindowsHookEx(_hookID);
}
return res;
}
And the Hook Code:
private static IntPtr HookCallback(int nCode, IntPtr wParam, IntPtr lParam)
{
if (nCode >= 0 && wParam == (IntPtr)WM_KEYDOWN)
{
int vkCode = Marshal.ReadInt32(lParam);
if (vkCode == VK_RETURN)
return (IntPtr)(-1);
}
return CallNextHookEx(_hookID, nCode, wParam, lParam);
}
Add these lines of code somewhere in your class (or in some static class that can be used by other classes):
Calling
RemoveAllKeyMessages()
does exactly what you want.