简体   繁体   中英

c# - how to disable hotkeys (except ctrl+alt+delete)

I have a winform application and I'd like to disable some key combinations during the execution of this application.

I want to disable all the key combinations ( Ctrl+Esc , Alt+Tab , WinKeys , etc), except Ctrl+Alt+Delete .

I use c# to program.

Thank you.

The correct way to do this is not using C# (or any programming language) at all.

Instead, you need to take advantage of Windows's built-in support for limited user accounts and other security-related provisions. You can lock down a computer so tightly that a user can't do anything. This type of thing is controlled by Group Policies, rather than something that an individual application should have any sort of control over.

You can ask more questions about Group Policy configuration and locking down a Windows machine on Server Fault , another Stack Exchange site that deals with this type of questions. But I recommend doing a search first to see if your question has already been answered there!


If you absolutely must do this in C#, your only solution is going to be a low-level keyboard hook. First because that's the only type of hook you can create in C#, and second because you need to be able to intercept and discard the key presses before any other application (including the OS itself) can receive and process them.

It's a good thing that you specifically excluded Ctrl+Alt+Delete in the question, because you're not going to be able to restrict that one, even with a low-level keyboard hook.

You'll find a sample implementation here on Stephen Toub's blog .

The trick is that you won't call the CallNextHookEx() function for the key presses that you wish to discard, which prevents the event information from being passed to the next application in the hook chain. As per the documentation for CallNextHookEx() :

Calling CallNextHookEx is optional, but it is highly recommended; otherwise, other applications that have installed hooks will not receive hook notifications and may behave incorrectly as a result. You should call CallNextHookEx unless you absolutely need to prevent the notification from being seen by other applications.

So you'll need to make sure that you do call the function for normal keyboard input, but not for that you wish to throw away. Instead of CallNextHookEx , you'll want to return 1— new IntPtr(1) .

In the sample code, all of that will happen in the HookCallback method, which is called each time a keyboard event is received. Use a switch statement on the vkCode value (which gives you the virtual key code of the key that was pressed) to determine which input you want to reject.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM