For example, with a Keyboard Hook =>
// Variables
static int hHook = 0;
HookProc KeyboardLLProcedure;
// Code
KeyboardLLProcedure = new HookProc(KeyboardLLProc);
hHook = SetWindowsHookEx(WH_KEYBOARD_LL, KeyboardLLProcedure, (IntPtr)0, 0);
// Procedure
public static int KeyboardLLProc(int nCode, IntPtr wParam, IntPtr lParam)
{
if ((nCode >= 0))
{
KBDLLHOOKSTRUCT pKBDLLHOOKSTRUCT = new KBDLLHOOKSTRUCT();
pKBDLLHOOKSTRUCT = (KBDLLHOOKSTRUCT)Marshal.PtrToStructure(lParam, pKBDLLHOOKSTRUCT.GetType());
if (wParam == (IntPtr)WM_KEYDOWN)
{
if (pKBDLLHOOKSTRUCT.vkCode == (short)Keys.D)
{
bool bKeyDown = (GetAsyncKeyState((int)Keys.LWin) & 0x8000) == 0x8000;
if (bKeyDown)
{
Console.Beep(8000, 10);
Console.WriteLine("[Win] + D intercepted");
return 1;
}
}
}
}
return nCode < 0 ? CallNextHookEx(hHook, nCode, wParam, lParam) : 0;
}
// Declarations
public const int WH_KEYBOARD_LL = 13;
public const int WM_KEYDOWN = 0x0100;
[DllImport("User32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
public static extern short GetAsyncKeyState(int nVirtKey);
[StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct KBDLLHOOKSTRUCT
{
public int vkCode;
public int scanCode;
public int flags;
public int time;
public uint dwExtraInfo;
}
public delegate int HookProc(int nCode, IntPtr wParam, IntPtr lParam);
[DllImport("User32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
public static extern int SetWindowsHookEx(int idHook, HookProc lpfn, IntPtr hInstance, int threadId);
[DllImport("User32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
public static extern bool UnhookWindowsHookEx(int idHook);
[DllImport("User32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
public static extern int CallNextHookEx(int idHook, int nCode, IntPtr wParam, IntPtr lParam);