Disable Keyboard Shortcuts and Combination Keys with C# (1): Disable frequently used hotkeys

来源:互联网 发布:我看网络用语走红 编辑:程序博客网 时间:2024/05/21 11:15

    Sometimes we may need disable keyboard shortcuts and combination keys in Windows. For instance, you want to turn a normal PC into a kiosk computer. A service program specified by the designer is running on it. Users can only see the interface of that program. Skipping out of the program interface and returning to normal Windows OS desktop are forbidden. To achieve this goal, a service program running in full screen mode need be developed in the first. It's easy to modify the Windows OS configure to autorun the program. But keyboard shortcuts and combination keys in Windows OS are annoying. The customized keyboard without hotkeys is expensive, so we have to try to find some methods to disable those keys by programming.
    In this article how to disable frequently used hotkeys with C# programming is introduced. Such hotkeys include: Alt + Tab, Alt +Esc, Alt + F4, Win, Ctrl + Esc. The ProcessCmdKey method can be overridden in .Net Framework. But only messages about modifier keys, including SHIFT, CTRL and ALT keys, can be intercepted. If intercepting more hotkeys is wanted, it is necessary to install a hook procedure by calling the SetWindowsHookEx function in 'User32.dll'. A C# example is given here. When it is run, the interface is as follows:


Step:
1. Create a C# Windows Forms application in Visual Studio. The project name is 'EnableOrDisableShortCutKeys';
2. Switch from code view to designer view, drag three buttons into the Windows Form from the toolbox, named them by StartButton, StopButton and ExitButton;
3. Modify the file 'Form1.cs', the source code is as listed below:

using System;using System.Windows.Forms;using System.Runtime.InteropServices;using System.Reflection;using System.Diagnostics;namespace EnableOrDisableShortCutKeys{    public partial class Form1 : Form    {        public const int WH_KEYBOARD_LL = 13;        public const int WM_KEYDOWN = 0x0100;        public const int WM_KEYUP = 0x0101;        public const int WM_SYSKEYDOWN = 0x0104;        public const int WM_SYSKEYUP = 0x0105;        public const int VK_TAB = 0x9;        public const int VK_MENU = 0x12; /* Alt key */        public const int VK_ESCAPE = 0x1B;        public const int VK_F4 = 0x73;        public const int VK_LWIN = 0x5B;        public const int VK_RWIN = 0x5C;        public const int VK_CONTROL = 0x11;        public const int VK_LCONTROL = 0xA2;        public const int VK_RCONTROL = 0xA3;        [StructLayout(LayoutKind.Sequential)]        public class KeyBoardHookStruct        {            public int vkCode;            public int scanCode;            public int flags;            public int time;            public int dwExtraInfo;        }        [DllImport("user32.dll", CallingConvention = CallingConvention.StdCall, SetLastError = true, CharSet = CharSet.Auto)]        public static extern int SetWindowsHookEx(int idHook, HookProc lpfn, IntPtr hInstance, int threadId);        [DllImport("user32.dll", CallingConvention = CallingConvention.StdCall, SetLastError = true, CharSet = CharSet.Auto)]        public static extern bool UnhookWindowsHookEx(int idHook);        [DllImport("user32.dll", CallingConvention = CallingConvention.StdCall, SetLastError = true, CharSet = CharSet.Auto)]        public static extern int CallNextHookEx(int idHook, int nCode, Int32 wParam, IntPtr lParam);        [DllImport("kernel32.dll", CallingConvention = CallingConvention.StdCall, SetLastError = true, CharSet = CharSet.Auto)]        public static extern IntPtr GetModuleHandle(string lpModuleName);        public delegate int HookProc(int nCode, Int32 wParam, IntPtr lParam);        static int hKeyboardHook = 0;        HookProc KeyboardHookProcedure;        public void HookStart()        {            if (hKeyboardHook == 0)            {                KeyboardHookProcedure = new HookProc(KeyboardHookProc);                using (Process curProcess = Process.GetCurrentProcess())                using (ProcessModule curModule = curProcess.MainModule)                {                    IntPtr hModule = GetModuleHandle(curModule.ModuleName);                    hKeyboardHook = SetWindowsHookEx(WH_KEYBOARD_LL, KeyboardHookProcedure, hModule, 0);                }                if (hKeyboardHook == 0)                {                    int error = Marshal.GetLastWin32Error();                    HookStop();                    throw new Exception("SetWindowsHookEx() function failed. " + "Error code: " + error.ToString());                }            }        }        public void HookStop()        {            bool retKeyboard = true;            if (hKeyboardHook != 0)            {                retKeyboard = UnhookWindowsHookEx(hKeyboardHook);                hKeyboardHook = 0;            }            if (!(retKeyboard))            {                throw new Exception("UnhookWindowsHookEx failed.");            }        }        private int KeyboardHookProc(int nCode, int wParam, IntPtr lParam)        {            KeyBoardHookStruct kbh = (KeyBoardHookStruct)Marshal.PtrToStructure(lParam, typeof(KeyBoardHookStruct));            bool bMaskKeysFlag = false;            switch (wParam)            {                case WM_KEYDOWN:                case WM_KEYUP:                case WM_SYSKEYDOWN:                case WM_SYSKEYUP:                    bMaskKeysFlag = ( (kbh.vkCode == VK_TAB) && (kbh.flags == 32) )      /* Tab + Alt */                                    | ((kbh.vkCode == VK_ESCAPE) && (kbh.flags == 32))   /* Esc + Alt */                                    | ((kbh.vkCode == VK_F4) && (kbh.flags == 32))       /* F4 + Alt */                                    | ( (kbh.vkCode == VK_LWIN) && (kbh.flags == 1) )    /* Left Win */                                    | ( (kbh.vkCode == VK_RWIN) && (kbh.flags == 1) )    /* Right Win */                                    | ( (kbh.vkCode == VK_ESCAPE) && (kbh.flags == 0) ); /* Ctrl + Esc */                    break;                default:                    break;            }            if (bMaskKeysFlag == true)            {                return 1;            }            else            {                return CallNextHookEx(hKeyboardHook, nCode, wParam, lParam);            }        }        public Form1()        {            InitializeComponent();        }        private void StartButton_Click(object sender, EventArgs e)        {            HookStart();        }        private void StopButton_Click(object sender, EventArgs e)        {            HookStop();        }        private void ExitButton_Click(object sender, EventArgs e)        {            Application.Exit();        }    }}


5. Build the program and run it.



0 0
原创粉丝点击