Search
Close this search box.

Disable Special Keys in Win App C#

Today, when I was planning to write an article on Grid View. I got a message from a very good friend of mine who is asking to disable the special keys(Windows Keys) in his application. When I start researching on it, I was thinking that it can be done using e.KeyChar but unfortunately, it is not showing any information about windows keys.

So in this post I will explain you, how can we disable the special keys (in our case windows keys) in C# Application.

1. Crete a c# windows application project
2. On the code behind of your default form add the following references

    using System.Diagnostics;
    using System.Runtime.InteropServices;

3. Now before the constructor of your form place the following code.

// 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;

4. Now add the following code on your constructor.

public Form1() {
  ProcessModule objCurrentModule =
      Process.GetCurrentProcess().MainModule;  // Get Current Module
  objKeyboardProcess = new LowLevelKeyboardProc(
      captureKey);  // Assign callback function each time keyboard process
  ptrHook = SetWindowsHookEx(
      13, objKeyboardProcess, GetModuleHandle(objCurrentModule.ModuleName),
      0);  // Setting Hook of Keyboard Process for current module

  InitializeComponent();
}

5. Now Implement the callback function

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

    if (objKeyInfo.key == Keys.RWin ||
        objKeyInfo.key == Keys.LWin)  // Disabling Windows keys
    {
      return (IntPtr)1;
    }
  }
  return CallNextHookEx(ptrHook, nCode, wp, lp);
}

6. Now go to your designer class and replace your dispose method.

/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed;
/// otherwise, false.</param>
protected override void Dispose(bool disposing) {
  if (disposing && (components != null)) {
    components.Dispose();
  }
  if (ptrHook != IntPtr.Zero) {
    UnhookWindowsHookEx(ptrHook);
    ptrHook = IntPtr.Zero;
  }
  base.Dispose(disposing);
}

So, in this way we can stop the windows key operation till your application is running.You can find the VS 2008 Source code here.

This article is part of the GWB Archives. Original Author: Agha Usman Ahmed

Related Posts