C# 操作键盘
窗体程序中有两个按钮按钮button1和button2
我要实现的功能
button1按下时,整个键盘变为不可用,不是单纯的屏蔽,就是不可用
button2按下时,整个键盘变为可用
请教各位高手,能实现么?
PS:我做的这个小程序类似于按键精灵,
到最后模拟键盘这步出现问题,
模拟键盘实现不了,我使用了两种方法都不行
keybd_event(0x27, 0, 0, 0);和SendKeys.Send("Right");
所以我想到把键盘屏蔽,然后在重新开启
------解决方案--------------------可以用键盘钩子
------解决方案--------------------http://www.cnblogs.com/hocylan/archive/2008/01/14/1038390.html
------解决方案--------------------调用底层系统钩子,建议去找一个转换键盘输入的WIN32DLL在C#中使用
------解决方案--------------------用API设置键盘钩子实现,以下是代码~自己修改一下就可以用了!
在按键事件中添加如下代码
private void button1_Click(object sender, EventArgs e)
{
Hook hook = new Hook();
hook.HookStart();
}
}
//////////////////////////////////////////
//在程序中添加键盘钩子子类
//////////////////////////
public class Hook
{
public Hook()
{ }
public const int WH_KEYBOARD = 13;
public const int WH_MOUSE_LL = 14;
[DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
public static extern int SetWindowsHookEx(int idHook, HookProc lpfn, IntPtr hInstance, int threadId);
[DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
public static extern bool UnhookWindowsHookEx(int idHook);
[DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
public static extern int CallNextHookEx(int idHook, int nCode, Int32 wParam, IntPtr lParam);
[DllImport("kernel32.dll")]
static extern int GetCurrentThreadId();
//定义一个委托
public delegate int HookProc(int nCode, Int32 wParam, IntPtr lParam);
static int hKeyboardHook = 0;
HookProc KeyboardHookProcedure;
//处理
private int KeyboardHookProc(int nCode, Int32 wParam, IntPtr lParam)
{
KeyMSG m = (KeyMSG)Marshal.PtrToStructure(lParam, typeof(KeyMSG));
if ((int)m.vkCode == 91)
{ return 1; }
return CallNextHookEx(hKeyboardHook, nCode, wParam, lParam);
}
// 安装钩子
public void HookStart()
{
if (hKeyboardHook == 0)
{
KeyboardHookProcedure = new HookProc(KeyboardHookProc);
hKeyboardHook = SetWindowsHookEx(WH_KEYBOARD, KeyboardHookProcedure,
Marshal.GetHINSTANCE(Assembly.GetExecutingAssembly().GetModules()[0]), GetCurrentThreadId());
// 如果设置钩子失败
if (hKeyboardHook == 0)
{
MessageBox.Show("set failed");
}
}
}
public struct KeyMSG
{
public int vkCode;
public int scanCode;
public int flags;
public int time;
public int dwExtraInfo;
}
}