欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

C# Winform 实现屏蔽键盘的win和alt+F4的实现代码

程序员文章站 2022-07-22 08:53:40
此时希望用户不能通过键盘alt+f4来结束程序及通过win的组合键对窗口进行操作。我在网上搜索了一下,采用全局键盘钩子的方法可以做到屏蔽用户对键盘的操作。。以下为相关代码,...
此时希望用户不能通过键盘alt+f4来结束程序及通过win的组合键对窗口进行操作。我在网上搜索了一下,采用全局键盘钩子的方法可以做到屏蔽用户对键盘的操作。。以下为相关代码,用到了form1_load事件和form1_formclosing事件:
复制代码 代码如下:

using system;
using system.collections.generic;
using system.componentmodel;
using system.data;
using system.drawing;
using system.text;
using system.windows.forms;
using system.runtime.interopservices;
using system.reflection;
namespace windowsapplication10
{
public partial class form1 : form
{
// 安装钩子
[dllimport("user32.dll")]
public static extern int setwindowshookex(int idhook, hookproc lpfn, intptr hinstance, int threadid);
// 卸载钩子
[dllimport("user32.dll")]
public static extern bool unhookwindowshookex(int idhook);
// 继续下一个钩子
[dllimport("user32.dll")]
public static extern int callnexthookex(int idhook, int ncode, int32 wparam, intptr lparam);
//声明定义
public delegate int hookproc(int ncode, int32 wparam, intptr lparam);
static int hkeyboardhook = 0;
hookproc keyboardhookprocedure;
public form1()
{
initializecomponent();
}
private void form1_load(object sender, eventargs e)
{
hookstart();
}
private void form1_formclosing(object sender, formclosingeventargs e)
{
hookstop();
}
// 安装钩子
public void hookstart()
{
if (hkeyboardhook == 0)
{
// 创建hookproc实例
keyboardhookprocedure = new hookproc(keyboardhookproc);
//定义全局钩子
hkeyboardhook = setwindowshookex(13, keyboardhookprocedure, marshal.gethinstance(assembly.getexecutingassembly().getmodules()[0]), 0);
if (hkeyboardhook == 0)
{
hookstop();
throw new exception("setwindowshookex failed.");
}
}
}
//钩子子程就是钩子所要做的事情。
private int keyboardhookproc(int ncode, int32 wparam, intptr lparam)
{
//这里可以添加别的功能的代码
return 1;
}
// 卸载钩子
public void hookstop()
{
bool retkeyboard = true;
if (hkeyboardhook != 0)
{
retkeyboard = unhookwindowshookex(hkeyboardhook);
hkeyboardhook = 0;
}
if (!(retkeyboard)) throw new exception("unhookwindowshookex failed.");
}
}
}

(注:该方法可以屏蔽win和alt+f4但是不能屏蔽ctrl+alt+del)