一个小程序需要屏蔽到ctrl和shift按键,折腾了两天,从JS到钩子皆搞不定,只有换思路了,有时间的话再研究下替换掉webbrowwer控件吧!郁闷死我了……虽然没搞定,但是截获更改键盘的方法记录下吧!
1.JAVAScript
document.onkeydown = function(){
if ((event.keyCode==16)||(event.keyCode==17)))||(event.keyCode==116))
{
event.keyCode=0;
event.returnValue=false;
}
}webbrowser执行JS
mshtml.IHTMLDocument2 document = (mshtml.IHTMLDocument2)wind.Document.DomDocument;
shtml.IHTMLWindow2 win = (mshtml.IHTMLWindow2)document.parentWindow;
win.execScript(”alert(’test’)”, “javascript”);
2.webbrowser
需要变相添加onkeydown监听事件
wind.Document.Body.KeyDown += new HtmlElementEventHandler(Body_KeyDown);
private void Body_KeyDown(object sender, HtmlElementEventArgs e)
{
/*if (e.ShiftKeyPressed || e.CtrlKeyPressed)
{
e.ReturnValue = false;
}*/
}当然一般控件是有onkeydown事件的,没必要这么麻烦……
2.键盘钩子
class Win32Hook
{
[DllImport("kernel32")]
public static extern int GetCurrentThreadId();
[DllImport("user32",CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
public static extern int SetWindowsHookEx(
HookType idHook,
HOOKPROC lpfn,
int hmod,
int dwThreadId);public enum HookType
{
WH_KEYBOARD = 2,
WA_KEYBOARD = 13
}public delegate int HOOKPROC(int nCode, int wParam, int lParam);
private static HOOKPROC hookproc;
public void SetHook()
{
hookproc = new HOOKPROC(this.MyKeyboardProc);
// set the keyboard hook
SetWindowsHookEx(HookType.WH_KEYBOARD,
hookproc,
0,
GetCurrentThreadId());
}public int MyKeyboardProc(int nCode, int wParam, int lParam)
{if ((nCode >= 0)&&((wParam == 16) || (wParam == 17)))
{
if (lParam > 0)
{
return 1;
}}
return 1;
}
}实例:
Win32Hook winhk = new Win32Hook();
winhk.SetHook();
上面三个方法都可以截获普通按键的,我也是{zh1}才知道系统按键,如果是不改驱动应该是没有办法解决了!只好暂时到此为止。另外web中我们其实是可以通过写成类似<a href=’javascript:window.open(……)’></a>的方法忽略掉ctrl和shift强制新窗口打开页面,更改js框架、换一个webbrowwer框架、虚拟机,解决方法还是有的,不过真丫的麻烦!