复制代码 代码如下:
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)
您可能感兴趣的文章:
如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!
网友评论