I am trying to understand a code which block some keys on the keyboard and allows only some exit paths, as compared to normal methods.
I have been able to get most of it, but there’s this part in which we are actually handling the keystrokes in this function.
Here’s the code:
public static IntPtr HookCallback(int nCode, IntPtr wParam, IntPtr lParam)
{
if (nCode >= 0)
{
bool Alt = (WinForms.Control.ModifierKeys & Keys.Alt) != 0;
bool Control = (WinForms.Control.ModifierKeys & Keys.Control) != 0;
//Prevent ALT-TAB and CTRL-ESC by eating TAB and ESC. Also kill Windows Keys.
int vkCode = Marshal.ReadInt32(lParam);
Keys key = (Keys)vkCode;
if (Alt && key == Keys.F4)
{
Application.Current.Shutdown();
return (IntPtr)1; //handled
}
if (key == Keys.LWin ||key == Keys.RWin) return (IntPtr)1; //handled
if (Alt && key == Keys.Tab) return (IntPtr)1; //handled
if (Alt && key == Keys.Space) return (IntPtr)1; //handled
if (Control && key == Keys.Escape)return (IntPtr)1;
if (key == Keys.None) return (IntPtr)1; //handled
if (key <= Keys.Back) return (IntPtr)1; //handled
if (key == Keys.Menu ) return (IntPtr)1; //handled
if (key == Keys.Pause) return (IntPtr)1; //handled
if (key == Keys.Help) return (IntPtr)1; //handled
if (key == Keys.Sleep) return (IntPtr)1; //handled
if (key == Keys.Apps) return (IntPtr)1; //handled
if (key >= Keys.KanaMode && key <= Keys.HanjaMode) return (IntPtr)1; //handled
if (key >= Keys.IMEConvert && key <= Keys.IMEModeChange) return (IntPtr)1; //handled
if (key >= Keys.BrowserBack && key <= Keys.BrowserHome) return (IntPtr)1; //handled
if (key >= Keys.MediaNextTrack && key <= Keys.OemClear) return (IntPtr)1; //handled
Debug.WriteLine(vkCode.ToString() + " " + key);
}
return InterceptKeys.CallNextHookEx(_hookID, nCode, wParam, lParam);
}
What does assigning boolean value to Alt with the & symbol mean in this line WinForms.Control.ModifierKeys & Keys.Alt ?
We have handled the keystrokes, but what the point about about returning an IntPtr of 1?
The
Keys.Altenumeration value is a bit mask that has the bit set that determines if the Alt modifier key is pressed.The
&operator does a bitwise and when used on twointorEnumvalues, so doing that on theWinForms.Control.ModifierKeyssingles out the bit for the Alt key.The method returns an
IntPtrvalue, so to return the value1that specifies that the key was handled, you have to cast it toIntPtr.