前言

有时候开发会遇到这样一个需求,软件需要屏蔽用户的组合快捷键或某些按键,避免强制退出软件,防止勿操作等。

原理

1、要实现组合键,按键拦截,需要用到user32.dll中的SetWindowsHookEx。

2、要拦截ctrl+alt+del,需要使用ntdll.dll的ZwSuspendProcess函数挂起winlogon程序,退出之后使用ZwResumeProcess恢复winlogon程序。

3、软件需要开启topMost,以及全屏,否则离开软件则拦截无效。

4、如果要实现热键监听(非焦点拦截),则需要用到user32.dll的RegisterHotKey以及UnregisterHotKey。

实现

1、Program类

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Windows.Forms; namespace LockForm
{
static class Program
{
/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
SuspendWinLogon();
Application.Run(new Form1());
ResumeWinLogon();
} [DllImport("ntdll.dll")]
public static extern int ZwSuspendProcess(IntPtr ProcessId);
[DllImport("ntdll.dll")]
public static extern int ZwResumeProcess(IntPtr ProcessId); private static void SuspendWinLogon()
{
Process[] pc = Process.GetProcessesByName("winlogon");
if (pc.Length > )
{
ZwSuspendProcess(pc[].Handle);
}
} private static void ResumeWinLogon()
{
Process[] pc = Process.GetProcessesByName("winlogon");
if (pc.Length > )
{
ZwResumeProcess(pc[].Handle);
}
}
}
}

2、Form1类

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows.Forms; namespace LockForm
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
} private void button1_Click(object sender, EventArgs e)
{
if (textBox1.Text == "")
{
Application.ExitThread();
}
else
{
webBrowser1.Navigate(textBox1.Text);
}
} private void Form1_Load(object sender, EventArgs e)
{
//webBrowser1.Navigate("https://baidu.com");
HookStart();
//this.TopMost = false;
//SuspendWinLogon();
} private void webBrowser1_NewWindow(object sender, CancelEventArgs e)
{
e.Cancel = true;
webBrowser1.Navigate(webBrowser1.Document.ActiveElement.GetAttribute("href"));
} private void button3_Click(object sender, EventArgs e)
{
webBrowser1.GoBack();
} private void button2_Click(object sender, EventArgs e)
{
webBrowser1.GoForward();
} private void button4_Click(object sender, EventArgs e)
{
webBrowser1.GoHome();
} private void webBrowser1_Navigated(object sender, WebBrowserNavigatedEventArgs e)
{
textBox1.Text = webBrowser1.Url.ToString();
} private void webBrowser1_Navigating(object sender, WebBrowserNavigatingEventArgs e)
{ } #region 键盘钩子 public delegate int HookProc(int nCode, int wParam, IntPtr lParam);//定义全局钩子过程委托,以防被回收(钩子函数原型)
HookProc KeyBoardProcedure; //定义键盘钩子的相关内容,用于截获键盘消息
static int hHook = ;//钩子函数的句柄
public const int WH_KEYBOARD = ;
//钩子结构函数
public struct KeyBoardHookStruct
{
public int vkCode;
public int scanCode;
public int flags;
public int time;
public int dwExtraInfo; }
//安装键盘钩子
public void HookStart()
{ if (hHook == )
{
//实例化一个HookProc对象
KeyBoardProcedure = new HookProc(Form1.KeyBoardHookProc); //创建线程钩子
hHook = Win32API.SetWindowsHookEx(WH_KEYBOARD, KeyBoardProcedure, Win32API.GetModuleHandle(Process.GetCurrentProcess().MainModule.ModuleName), ); //如果设置线程钩子失败
if (hHook == )
{
HookClear();
}
}
} //取消钩子
public void HookClear()
{
bool rsetKeyboard = true;
if (hHook != )
{
rsetKeyboard = Win32API.UnhookWindowsHookEx(hHook);
hHook = ;
}
if (!rsetKeyboard)
{
throw new Exception("取消钩子失败!");
}
}
//对截获的键盘操作的处理
public static int KeyBoardHookProc(int nCode, int wParam, IntPtr lParam)
{
if (nCode >= )
{
KeyBoardHookStruct kbh = (KeyBoardHookStruct)Marshal.PtrToStructure(lParam, typeof(KeyBoardHookStruct)); if (kbh.vkCode == )//截获左边WIN键
{
return ;
}
if (kbh.vkCode == )//截获右边WIN键
{
return ;
}
if (kbh.vkCode == (int)Keys.Escape && (int)Control.ModifierKeys == (int)Keys.Control)//截获Ctrl+ESC键
{
return ;
}
if (kbh.vkCode == (int)Keys.Escape && (int)Control.ModifierKeys == (int)Keys.Alt)
{
return ;
}
if (kbh.vkCode == (int)Keys.F4 && (int)Control.ModifierKeys == (int)Keys.Alt)//截获ALT+F4
{
return ;
}
if (kbh.vkCode == (int)Keys.Tab && (int)Control.ModifierKeys == (int)Keys.Alt)//截获ALT+TAB
{
return ;
}
if (kbh.vkCode == (int)Keys.Delete&&(int)Control.ModifierKeys == (int)Keys.Control + (int)Keys.Alt)
{
return ;
}
if ( kbh.vkCode == (int) Keys.Escape && (int) Control.ModifierKeys == (int) Keys.Control + (int) Keys.Alt ) /* 截获Ctrl+Shift+Esc */
{
return ;
} } return Win32API.CallNextHookEx(hHook, nCode, wParam, lParam);
}
#endregion
}
}

3、声明windows api

        //设置钩子
[DllImport("user32.dll")]
public static extern int SetWindowsHookEx(int idHook, LockForm.Form1.HookProc lpfn, IntPtr hInstance, int threadID); //卸载钩子
[DllImport("user32.dll", CallingConvention = CallingConvention.StdCall)]
public static extern bool UnhookWindowsHookEx(int idHook); //调用下一个钩子
[DllImport("user32.dll")]
public static extern int CallNextHookEx(int idHook, int nCode, int wParam, IntPtr lParam);

PS:

windows api查询

http://www.pinvoke.net/index.aspx

demo下载

链接:http://pan.baidu.com/s/1jGpOvsE 密码:dbj2

c# 屏蔽快捷键的更多相关文章

  1. C# 通过Hook的方法 屏蔽快捷键

     #region 屏蔽Windows功能键(快捷键)         public delegate int HookProc(int nCode, int wParam, IntPtr lParam ...

  2. wpf屏蔽快捷键alt+space,alt+F4

    /// <summary>        /// 阻止 alt+f4和alt+space 按键        /// </summary>        /// <par ...

  3. c#实现word,winWordControl 文档不允许复制、粘贴、隐藏工具栏、快捷保存

    1.隐藏工具栏 //隐藏工具栏 ; i <= winWordControl1.document.CommandBars.Count; i++) { winWordControl1.documen ...

  4. c++屏蔽Win10系统快捷键

    很久之前实现的功能,也是参考其他人的实现,时间太久,具体参考哪里已经记不得了. 这里不仅能屏蔽一般的快捷键,还可以屏蔽ctrl+atl+del. ; HHOOK keyHook = NULL; HHO ...

  5. 如何屏蔽SkylineGlobe提供的三维地图控件上的快捷键

    SkyllineGlobe提供的 <OBJECT ID=" TerraExplorer3DWindow" CLASSID="CLSID:3a4f9192-65a8- ...

  6. win7屏蔽ctrl+alt+up/down快捷键/ (eclipse冲突)

    win7屏蔽ctrl+alt+up/down快捷键/   Eclipse有个非常好用的快捷键(当然Eclipse好用的快捷键有N个)Ctrl+Alt+UP/DOWN,用于复制当前行的内容,用法很简单, ...

  7. Jquery屏蔽浏览器的F1-F12快捷键,在IE,GOOGLE下测试均无问题

    在网上找了找,很多都是js实现的,东找西找,再加上自己的想法也勉强的完成了,直接看代码 <script type="text/javascript" src="Sc ...

  8. windowsclient开发--使用、屏蔽一些快捷键

    每一个windowsclient都有自己的一些快捷键,有的是windows系统提供的. 今天就要与大家分享一下.在windowsclient开发过程中对按键的处理. ESC按键 Duilib这个库中, ...

  9. C# 屏蔽Ctrl Alt Del 快捷键方法+屏蔽所有输入

    原文:C# 屏蔽Ctrl Alt Del 快捷键方法+屏蔽所有输入 Win32.cs /* * * FileCreate By Bluefire * Used To Import WindowsApi ...

随机推荐

  1. 装饰(Decorator)模式

    一. 装饰(Decorator)模式 装饰(Decorator)模式又名包装(Wrapper)模式[GOF95].装饰模式以对客户端透明的方式扩展对象的功能,是继承关系的一个替代方案. 二. 装饰模式 ...

  2. c编译错误[Error] ld returned 1 exit status 解决

    [Error] ld returned exit status 编译的过程中出现这个错误极有可能是因为函数名错误引起的,因此回到源码中观察函数名,尤其是那些库函数中的函数.

  3. linux系统root用户登录提示“鉴定故障”的解决办法

    同事第一次创建虚拟机,遇到此问题,此前我未曾遇到,搜索到的解决办法记录在此,以防之后忘记. 一.重启系统解决(搜索到的该解决办法较多):https://www.cnblogs.com/lippor/p ...

  4. 题解 CF500D 【New Year Santa Network】

    题目链接 这道题首先是要看看该如何化简,先把三元组化成二元组. 之后统计经过某条边的 次数$*$权值  的和. 最后除以总基数 $tot$ 其中,每条边被计算的次数为 子树的点数$*$非子树的点数 ( ...

  5. 【问题记录】在执行js的时候报错:missing ) after argument list

    在执行个js语句时候报错: 报错语句: js('document.querySelector("[class] [tabindex='0']:nth-child(2) span") ...

  6. What Goes Up UVA - 481 LIS+打印路径 【模板】

    打印严格上升子序列: #include<iostream> #include<cstdio> #include<algorithm> #include<cst ...

  7. 3.1、Factorization Machine模型

    Factorization Machine模型 在Logistics Regression算法的模型中使用的是特征的线性组合,最终得到的分隔超平面属于线性模型,其只能处理线性可分的二分类问题,现实生活 ...

  8. 精通 WPF UI Virtualization (提升 OEA 框架中 TreeGrid 控件的性能)

    原文:精通 WPF UI Virtualization (提升 OEA 框架中 TreeGrid 控件的性能) 本篇博客主要说明如何使用 UI Virtualization(以下简称为 UIV) 来提 ...

  9. 19年PDYZ冬令营游记

    我和卓越的那些事 ——2019年平度一中卓越计划冬令营   题前记: 正月十三那天,刚看完<流浪地球>,便接到了一个电话,老妈告诉我竟然一中组织了一个冬令营,并且起了一个很好的名字“卓越计 ...

  10. [DEBUG]-[org.mybatis.spring.SqlSessionFactoryBean.buildSqlSessionFactory(SqlSessionFactoryBean.java:431)] 一直在创建sqlsession工厂原因

    今天在做开发项目的时候出现一直在控台输出创建sqlsessionfactory'这个代码, tomcat一直在控制台上输出这个内容无法停止下来,那么到底是什么原因呢, 我们可以在输出信息上看到有个wa ...