Geeks With Blogs

News

Agha Usman Ahmed JILAWATAN

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

   1: using System.Diagnostics;
   2: using System.Runtime.InteropServices;

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

   1: // Structure contain information about low-level keyboard input event
   2: [StructLayout(LayoutKind.Sequential)]
   3: private struct KBDLLHOOKSTRUCT
   4: {
   5:     public Keys key;
   6:     public int scanCode;
   7:     public int flags;
   8:     public int time;
   9:     public IntPtr extra;
  10: }
  11:  
  12: //System level functions to be used for hook and unhook keyboard input
  13: private delegate IntPtr LowLevelKeyboardProc(int nCode, IntPtr wParam, IntPtr lParam);
  14: [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
  15: private static extern IntPtr SetWindowsHookEx(int id, LowLevelKeyboardProc callback, IntPtr hMod, uint dwThreadId);
  16: [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
  17: private static extern bool UnhookWindowsHookEx(IntPtr hook);
  18: [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
  19: private static extern IntPtr CallNextHookEx(IntPtr hook, int nCode, IntPtr wp, IntPtr lp);
  20: [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
  21: private static extern IntPtr GetModuleHandle(string name);
  22: [DllImport("user32.dll", CharSet = CharSet.Auto)]
  23: private static extern short GetAsyncKeyState(Keys key);
  24:  
  25:  
  26: //Declaring Global objects
  27: private IntPtr ptrHook;
  28: private LowLevelKeyboardProc objKeyboardProcess; 

4. Now add the following code on your constructor.

   1: public Form1()
   2: {
   3:     ProcessModule objCurrentModule = Process.GetCurrentProcess().MainModule; //Get Current Module
   4:     objKeyboardProcess = new LowLevelKeyboardProc(captureKey); //Assign callback function each time keyboard process
   5:     ptrHook = SetWindowsHookEx(13, objKeyboardProcess, GetModuleHandle(objCurrentModule.ModuleName), 0); //Setting Hook of Keyboard Process for current module
   6:  
   7:  
   8:     InitializeComponent();
   9: }

5. Now Implement the callback function

   1: private IntPtr captureKey(int nCode, IntPtr wp, IntPtr lp)
   2: {
   3:     if (nCode >= 0)
   4:     {
   5:         KBDLLHOOKSTRUCT objKeyInfo = (KBDLLHOOKSTRUCT)Marshal.PtrToStructure(lp, typeof(KBDLLHOOKSTRUCT));
   6:  
   7:         if (objKeyInfo.key == Keys.RWin || objKeyInfo.key == Keys.LWin) // Disabling Windows keys
   8:         {
   9:             return (IntPtr)1;
  10:         }
  11:     }
  12:     return CallNextHookEx(ptrHook, nCode, wp, lp);
  13: }

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

   1: /// <summary>
   2: /// Clean up any resources being used.
   3: /// </summary>
   4: /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
   5: protected override void Dispose(bool disposing)
   6: {
   7:     if (disposing && (components != null))
   8:     {
   9:  
  10:         components.Dispose();
  11:     }
  12:     if (ptrHook != IntPtr.Zero)
  13:     {
  14:         UnhookWindowsHookEx(ptrHook);
  15:         ptrHook = IntPtr.Zero;
  16:     }
  17:     base.Dispose(disposing);
  18: }

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.

Posted on Sunday, April 26, 2009 11:32 PM c# , .net | Back to top


Comments on this post: Disable Special Keys in Win App C#

# re: Disable Special Keys in Win App C#
Requesting Gravatar...
Very nice! This is just the code i needed for my application! Thank you for sharing it!
Left by Alex Colson on May 29, 2009 9:57 PM

# re: Disable Special Keys in Win App C#
Requesting Gravatar...
Hey, very nice thanks, this helped my project allot!

Is it possible to disable any keys with this? for example Ctrl + Alt + Esc?

Thanks!
Left by David on Jul 26, 2009 2:02 AM

# re: Disable Special Keys in Win App C#
Requesting Gravatar...
Thank you!!

Very good.
Left by Ehitel Rodriguez on Dec 14, 2009 5:22 PM

# re: Disable Special Keys in Win App C#
Requesting Gravatar...
hi
am using this code it disable the window key in form open but never enable when we closed the form
what i do
pls solve this problem
u can send the the idea on my id
pls.. help me...

thanks in advanced.

my e-mail id
sonu_singh4636@yahoo.com
Left by sujeet on Dec 23, 2009 12:32 AM

# re: Disable Special Keys in Win App C#
Requesting Gravatar...
thank you very very much for such a great code snipet....
i was facing thix problem from quite a long time
thanx again
best regards
ahsan Sarfraz
Left by Ahsan Sarfraz on Jan 29, 2010 8:39 PM

# re: Disable Special Keys in Win App C#
Requesting Gravatar...
thank you vary much !!
Left by Tanka on Feb 01, 2010 11:16 PM

# re: Disable Special Keys in Win App C#
Requesting Gravatar...
Hi,The Method Quite Good
Do You Know How to Disable Alt+Tab
Thank You!
Left by Tony Xu on Feb 27, 2010 6:22 AM

# re: Disable Special Keys in Win App C#
Requesting Gravatar...
Thank you so much... for a great code represented very easily.
Left by Pritesh Mane on Mar 29, 2010 1:37 AM

# re: Disable Special Keys in Win App C#
Requesting Gravatar...
Good job man!
Left by Aziz on Aug 13, 2010 3:53 AM

# re: Disable Special Keys in Win App C#
Requesting Gravatar...
Thank you very much.
perfect
Left by atervan on Sep 21, 2010 6:52 PM

# re: Disable Special Keys in Win App C#
Requesting Gravatar...
How do you disable a TAB but enable an ALT + TAB?

Left by Lister on Nov 24, 2010 7:03 PM

# Couldn't get to work: Disable Special Keys in Win App C#
Requesting Gravatar...
I couldn't get this to work with VS 2008 in WPF application. Keys was unrecognized everywhere, so I changed it to Key (e.g. Key.LWin).

When debugging objKeyInfo.key has value 'F2' when pressing LWin and 'OemBackTab' when pressing RWin. When using these values I can intercept LWin, but RWin still opens Start Menu.

Might be some localization setting, I'm using finnish keyboard layout.
Left by VV on Dec 27, 2010 12:06 AM

# Works: Disable Special Keys in Win App C#
Requesting Gravatar...
Answering to myself: WPF and Windows Forms have different key enumerators. WF Keys and WPF Key are two different things.

I added this using line:
using Keys = System.Windows.Forms.Keys;
and Windows keys are disabled. Thank you for your example!
Left by VV on Dec 27, 2010 12:44 AM

# re: Disable Special Keys in Win App C#
Requesting Gravatar...
I used this code and it works, but something happen and now my windows key is not working. :( both left and right key.

I am having this problem since yesterday i am practically pulling my hair off :( is there a way to manually release the key?

I noticed that in the code UnhookWindowsHookEx(ptrHook)
the ptrHook value is always different everytime you run the application. i wonder if there is a thread thats is still running that prevents me on using the windows key. i restarted my PC and still no luck. any help will be appreciated. thanks
Left by Cray on Mar 09, 2011 8:47 PM

# re: Disable Special Keys in Win App C#
Requesting Gravatar...
Thank you.It helps a lot on our SAD system.:)
Left by alma on Apr 03, 2011 6:33 PM

# re: Disable Special Keys in Win App C#
Requesting Gravatar...
voy aver como funciona esperom ayude de muxo thanks you...
Left by maxx on May 23, 2011 4:39 AM

# re: Disable Special Keys in Win App C#
Requesting Gravatar...
Awesome. Really handy and efficient code. Thanks.
Left by Shahram Khorsand on Jun 22, 2011 3:43 AM

# re: Disable Special Keys in Win App C#
Requesting Gravatar...
I used this code and it works, but something happen and now my windows key is not working. :( both left and right key.

I am having this problem since yesterday i am practically pulling my hair off :( is there a way to manually release the key?
Left by housse ipad 2 on Jun 28, 2011 6:27 AM

# re: Disable Special Keys in Win App C#
Requesting Gravatar...
I noticed that in the code UnhookWindowsHookEx(ptrHook)
the ptrHook value is always different everytime you run the application. i wonder if there is a thread thats is still running that prevents me on using the windows key. i restarted my PC and still no luck. any help will be appreciated
Left by housse samsung galaxy s2 on Jun 28, 2011 6:27 AM

# Disable Special Keys in Win App C#
Requesting Gravatar...
Thankyou verymuch
God bless you
Left by Vikas Bansal on Aug 12, 2011 8:18 PM

# re: Disable Special Keys in Win App C#
Requesting Gravatar...
Error 1 The name 'IntPtr' does not exist in the current context

this error comes on the following page:
Form1.Designer.cs
Can you help me?
Left by Mrityunjaya Pathak on Dec 13, 2011 10:49 PM

# re: Disable Special Keys in Win App C#
Requesting Gravatar...
Great Work......Thank you So much.. I'm going to use this for disable automatically pressing Enter key on bar-code Saner
Left by Harith on Jan 16, 2012 12:49 AM

# re: Disable Special Keys in Win App C#
Requesting Gravatar...
Would like to enable keys. how do i do this
Left by nigee on Jan 29, 2012 5:28 AM

# re: Disable Special Keys in Win App C#
Requesting Gravatar...
Wow *0* Amazing ,, Thank you very much.
Left by ArMut on Feb 13, 2012 8:22 AM

# re: Disable Special Keys in Win App C#
Requesting Gravatar...
No its is not working well, because my space key and Alt+F4 key is working, so i think its is not complete article
Left by Parveen Rathi on Feb 28, 2012 7:25 PM

# re: Disable Special Keys in Win App C#
Requesting Gravatar...
How to disable/block the complete keyboard. How to achieve this, Thanks in Advance...
Left by E. Arasu on Mar 17, 2012 12:50 AM

# re: Disable Special Keys in Win App C#
Requesting Gravatar...
Thank you that was really useful, is it working on Windows CE? it run .Net V3.5
I tried to compile it on a Smart Phone application but I get this error:
the type or namespace name "ProcessModule" could not be found
Left by Pouri on Apr 01, 2012 8:02 PM

# re: Disable Special Keys in Win App C#
Requesting Gravatar...
This is such a great piece of code. Probably you should put this in Codeproject or stackoverflow! Those assholes could'nt answer this problem of disabling the windows key. :D thanks dude.
Left by sid on Jul 14, 2012 11:17 PM

# re: Disable Special Keys in Win App C#
Requesting Gravatar...
Perfect... Thank you very much
Left by Kemal on Aug 09, 2012 11:38 PM

# re: Disable Special Keys in Win App C#
Requesting Gravatar...
Thank you for this great code but I have to disable the windows+D key for the windows form. how to do this?
Left by Chetan on Aug 16, 2012 8:22 PM

# re: Disable Special Keys in Win App C#
Requesting Gravatar...
hi , please i need help with turning off the control key ..(Ctrl) it is always pressed down ..so whenever i wirite a letter it goes for the short cut function ....knowing that i have windos seven ,and the laptop is hp ..thanks in advance
Left by heba on Sep 23, 2012 11:23 AM

# re: Disable Special Keys in Win App C#
Requesting Gravatar...
Hi i try this code in win7 but it can not disable the win key such as: alt+ctrl+del and ctrl+shift+esc
plz help me
i want a code or dll file when run disable keyboard like cut keyboard cable :D
some one say too me : you must write a c++ file and input that file in c# with dll
thanks
Left by Alireza on Oct 29, 2012 9:35 PM

# re: Disable Special Keys in Win App C#
Requesting Gravatar...
Thank you for the detailed explanation to the code! But, this is not working while the user is opening MS Word after the application. May be an issue with Hook Chain. Any advice?
Left by Soumyakanta Panda on Nov 11, 2012 6:10 PM

# re: Disable Special Keys in Win App C#
Requesting Gravatar...
excellent!!!!!!!!!!, thank you, it is very good.
Left by Mauricio on Nov 15, 2012 3:59 PM

# re: Disable Special Keys in Win App C#
Requesting Gravatar...
Thank you :) (TR) Türkiyeden selamlar(hi) :)
Left by Kemal KIZILKAYA on Feb 16, 2013 9:41 AM

# re: Disable Special Keys in Win App C#
Requesting Gravatar...
This is exactly what i was looking for, ill bookmark your blog and keep as a Fan =).

Thank you very much.
Left by Rafael Ramirez on Mar 07, 2013 7:21 AM

# re: Disable Special Keys in Win App C#
Requesting Gravatar...
You are perfect. Thank you very very very much. That code is incredible.
Left by Mert on Jul 04, 2013 7:05 AM

# re: Disable Special Keys in Win App C#
Requesting Gravatar...
Thank you so much, what I want I just got here thanks again :)
Left by Onkar on Aug 06, 2013 11:02 PM

# re: Disable Special Keys in Win App C#
Requesting Gravatar...
What I want I just got here thanks again :)
thank you so much :)
Left by Onkar on Aug 06, 2013 11:02 PM

# re: Disable Special Keys in Win App C#
Requesting Gravatar...
Very nice, it helped me.
Left by madhukar jha on Aug 29, 2013 7:42 PM

# re: Disable Special Keys in Win App C#
Requesting Gravatar...
Very nice, it helped me alot.
Left by madhukar jha on Aug 29, 2013 7:43 PM

# re: Disable Special Keys in Win App C#
Requesting Gravatar...
its not work for Ctrl+Alt+Delete.PLease give me any sample code to disable it.
Left by Surendra on Sep 25, 2013 10:59 PM

# re: Disable Special Keys in Win App C#
Requesting Gravatar...
hi i used this code for disable and enable keys and working good for 4 and 5 times after that i got error like
"CallbackOnCollectedDelegate was detected
Message: A callback was made on a garbage collected delegate of type 'AppsNet!AppsNet.frmMain+LowLevelKeyboardProc::Invoke'. This may cause application crashes, corruption and data loss. When passing delegates to unmanaged code, they must be kept alive by the managed application until it is guaranteed that they will never be called."

plz let me know...
Left by sri on Oct 21, 2013 8:59 PM

# re: Disable Special Keys in Win App C#
Requesting Gravatar...
I am triyin to do this in a Windows CE 6.0 device, but the compiler generate errors! at this line in the constructor:
ProcessModule objCurrentModule = Process.GetCurrentProcess().MainModule;

Error 2 'System.Diagnostics.Process' does not contain a definition for 'MainModule' and no extension method 'MainModule' accepting a first argument of type 'System.Diagnostics.Process' could be found (are you missing a using directive or an assembly reference?)
Left by Koly on Jan 14, 2014 4:35 AM

# re: Disable Special Keys in Win App C#
Requesting Gravatar...
Hi.

I am getting te below error:

Error 1 The name 'IntPtr' does not exist in the current context

Error comes from the following page:
designer Class.
Can you please help me?

Thanks
Bala
Left by Bala on Jan 20, 2014 3:16 AM

# re: Disable Special Keys in Win App C#
Requesting Gravatar...
The keys are still enabled. even the code given by you was unable to lock the keyboard or mouse.
And i also want to enable it on a certain validation. please help me in it.
Left by manish on Apr 30, 2014 1:21 AM

# re: Disable Special Keys in Win App C#
Requesting Gravatar...
Hello,I used code this but its not working in windows7(Ultimate).How can i solve this problem. Had you tried in Windows7 yet?
Left by Sunil Deshalahre on May 20, 2014 6:29 AM

# re: Disable Special Keys in Win App C#
Requesting Gravatar...
Thank you so much. Great job...
Left by Namrata Mane on Jul 17, 2014 6:09 PM

# Error 1 The name 'IntPtr' does not exist in the current context
Requesting Gravatar...
add the namespace into designer class
using System;

Problem Solve
Left by mahdndra on Aug 13, 2014 7:57 PM

Your comment:
 (will show your gravatar)


Copyright © Agha Usman Ahmed | Powered by: GeeksWithBlogs.net | Join free