如何禁用或锁定Windows按钮?
使用 windows hooks 比修改注册表要干净得多。此外,有时人们会设置自己的个性化扫描码图,覆盖它们并不是一件好事。
要使用 windows 键钩函数,您需要 DllImport 几个 winapi 函数:
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern IntPtr GetModuleHandle(string lpModuleName);
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern IntPtr SetWindowsHookEx(int idHook, HookHandlerDelegate lpfn, IntPtr hMod, uint dwThreadId);
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool UnhookWindowsHookEx(IntPtr hhk);
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern IntPtr CallNextHookEx(IntPtr hhk, int nCode, IntPtr wParam, ref KBDLLHOOKSTRUCT lParam);
[DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true, CallingConvention = CallingConvention.Winapi)]
public static extern short GetKeyState(int keyCode);
Run Code Online (Sandbox Code Playgroud)
可以在CodeProject上找到相当完整的解释和演练。这是来自该示例的自包含类文件的直接链接,该文件可以执行所有操作(如果您使用 WPF,要使其编译干净将需要您手动引用 System.Windows.Forms dll 或仅更改 'System.Windows.Forms.dll 文件)。 Forms.Keys 对 System.Windows.Input.Key 的引用应该可以工作)。
请记住调用 UnhookWindowsHookEx()(该类在 Dispose() 中执行此操作)以取消您的捕获,否则人们会讨厌您。
/// <summary>
/// Security routines related to the Windows Key on a standard personal computer Keyboard
/// </summary>
public static class WindowsKey {
/// <summary>
/// Disables the Windows Key
/// </summary>
/// <remarks>May require the current user to logoff or restart the system</remarks>
public static void Disable() {
RegistryKey key = null;
try {
key = Registry.LocalMachine.OpenSubKey("System\\CurrentControlSet\\Control\\Keyboard Layout", true);
byte[] binary = new byte[] {
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x03,
0x00,
0x00,
0x00,
0x00,
0x00,
0x5B,
0xE0,
0x00,
0x00,
0x5C,
0xE0,
0x00,
0x00,
0x00,
0x00
};
key.SetValue("Scancode Map", binary, RegistryValueKind.Binary);
}
catch (System.Exception ex) {
Debug.Assert(false, ex.ToString());
}
finally {
key.Close();
}
}
/// <summary>
/// Enables the Windows Key
/// </summary>
/// <remarks>May require the current user to logoff or restart the system</remarks>
public static void Enable() {
RegistryKey key = null;
try {
key = Registry.LocalMachine.OpenSubKey("System\\CurrentControlSet\\Control\\Keyboard Layout", true);
key.DeleteValue("Scancode Map", true);
}
catch (System.Exception ex) {
Debug.Assert(false, ex.ToString());
}
finally {
key.Close();
}
}
}
Run Code Online (Sandbox Code Playgroud)
转自:http://Www.CnBlogs.Com/WebEnh/
如果想下次快速找到我,记得点下面的关注哦!
本博客Android APP 下载 |
支持我们就给我们点打赏 |
支付宝打赏 支付宝扫一扫二维码 |
微信打赏 微信扫一扫二维码 |
如果想下次快速找到我,记得点下面的关注哦!