How to Suppress task switch keys (winkey, alt-tab, alt-esc, ctrl-esc) using low-level keyboard hook in c#

17,412

Solution 1

I've got the complete code to disable Windows Key , Alt + Tab and so on..

And now I'm providing the following code as a reference for others:

    /* Code to Disable WinKey, Alt+Tab, Ctrl+Esc Starts Here */

    // Structure contain information about low-level keyboard input event 
    [StructLayout(LayoutKind.Sequential)]
    private struct KBDLLHOOKSTRUCT
    {
        public Keys key;
        public int scanCode;
        public int flags;
        public int time;
        public IntPtr extra;
    }
    //System level functions to be used for hook and unhook keyboard input  
    private delegate IntPtr LowLevelKeyboardProc(int nCode, IntPtr wParam, IntPtr lParam);
    [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    private static extern IntPtr SetWindowsHookEx(int id, LowLevelKeyboardProc callback, IntPtr hMod, uint dwThreadId);
    [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    private static extern bool UnhookWindowsHookEx(IntPtr hook);
    [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    private static extern IntPtr CallNextHookEx(IntPtr hook, int nCode, IntPtr wp, IntPtr lp);
    [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    private static extern IntPtr GetModuleHandle(string name);
    [DllImport("user32.dll", CharSet = CharSet.Auto)]
    private static extern short GetAsyncKeyState(Keys key);
    //Declaring Global objects     
    private IntPtr ptrHook;
    private LowLevelKeyboardProc objKeyboardProcess;

    private IntPtr captureKey(int nCode, IntPtr wp, IntPtr lp)
    {
        if (nCode >= 0)
        {
            KBDLLHOOKSTRUCT objKeyInfo = (KBDLLHOOKSTRUCT)Marshal.PtrToStructure(lp, typeof(KBDLLHOOKSTRUCT));

            // Disabling Windows keys 

            if (objKeyInfo.key == Keys.RWin || objKeyInfo.key == Keys.LWin || objKeyInfo.key == Keys.Tab && HasAltModifier(objKeyInfo.flags) || objKeyInfo.key == Keys.Escape && (ModifierKeys & Keys.Control) == Keys.Control)     
            {
                return (IntPtr)1; // if 0 is returned then All the above keys will be enabled
            }
        }
        return CallNextHookEx(ptrHook, nCode, wp, lp);
    }

    bool HasAltModifier(int flags)
    {
        return (flags & 0x20) == 0x20;
    }

    /* Code to Disable WinKey, Alt+Tab, Ctrl+Esc Ends Here */

Then Inside the Form_Load();

   private void Form_Load(object sender, EventArgs e)
   {
      ProcessModule objCurrentModule = Process.GetCurrentProcess().MainModule;
      objKeyboardProcess = new LowLevelKeyboardProc(captureKey);
      ptrHook = SetWindowsHookEx(13, objKeyboardProcess, GetModuleHandle(objCurrentModule.ModuleName), 0);  
   }

Solution 2

You can use the OnKeyDown event to capture the keys pressed and suppress the ones you don't want to allow.

Scott Hanselman's BabySmash application does disable most key strokes like alt-tab alt-esc, etc. Most of the source and development can be found on his blog. The source is on GitHub. In the source, you will see he InterceptKeys class that uses many win32 calls to get low level hooks to the keys pressed. He then handles these in HookCallback in the App.xaml.cs file. Hope this helps.

Similar Question

Another Similar

Share:
17,412
ASr..
Author by

ASr..

Life is to Live..

Updated on June 18, 2022

Comments

  • ASr..
    ASr.. about 2 years

    Can anyone please tell me how to disable the task switch keys using c#

    • Fosco
      Fosco almost 14 years
      Why would you want to do this?
    • Chris Marisic
      Chris Marisic almost 14 years
      Any type of kiosk application... Valid question not sure why the DV, this is probably a duplicate though.
    • yoyo
      yoyo over 8 years
      Most PC games do this. Exclusive fullscreen gets better performance on many systems, and who wants Skype chat popping up while you're trying to play your favourite game?
  • Mike Ohlsen
    Mike Ohlsen almost 14 years
    added another similar SO question. You cant catch ctrl-alt-del, and probably not alt-tab, but most others. Should be able to do win key.
  • Mike Ohlsen
    Mike Ohlsen almost 14 years
    the babysmash example does what you are looking for
  • ChrisV
    ChrisV almost 14 years
    Alt-Tab is catchable, but not recommended. Ctrl-Alt-Del cannot be trapped in user mode. Full stop.
  • Carlos Blanco
    Carlos Blanco over 11 years
    I get this error Error System.Windows.Input.ModifierKeys' is a 'type' but is used like a 'variable
  • Carlos Blanco
    Carlos Blanco over 11 years
    I ended up using this check if (objKeyInfo.key == Keys.RWin || objKeyInfo.key == Keys.LWin || objKeyInfo.key == Keys.Tab && HasAltModifier(objKeyInfo.flags) || objKeyInfo.key == Keys.Escape && (Keyboard.Modifiers & ModifierKeys.Control) != 0)
  • Niloo
    Niloo over 10 years
    I use this code, but i get error Attempted to read or write protected memory. This is often an indication that other memory is corrupt
  • kad81
    kad81 over 10 years
    Works well except Alt+Esc was still causing problems (tried CarlosBlanco's solution and it didn't fix it). Adding the condition objKeyInfo.key == Keys.Escape && HasAltModifier(objKeyInfo.flags) worked, however.
  • WolfyD
    WolfyD almost 7 years
    Amazing solution, works great except for some reason after I exit alt + tab is still disabled. I tried using UnhookWindowsHookEx but it didn't seem to work
  • AntiqTech
    AntiqTech over 2 years
    Thanks a lot 🙏 Just that I needed to run the exe as Administrator.