现在希望实现一个接口,有如下需求:
1.可以截获按下或松开的按键(无论焦点是否在程序主窗体上)
2.截获按键时应可以获得一些信息,包括:按键的值,按下还是松开按键,是否将按下键操作传递给消息链的下一个对象。
接口已经写好了,只要就行了。实现时可以用任何语言,不论是C#还是C++或是使用其他dll文件,只要我能拿来用就行了(我使用的是C#)。
如果已完成可以上传到网上,给出下载链接就行,往大家予以帮助。PS:我用C#写的全局钩子不打完善,虽然可以截获到按键信息,但是顺序太靠后了,例如在文本框中输入“a”,我能截获到但是如果拦截输入,文本框仍然会输入“a”,使用语句“return 0;”也不行。接口声明如下:namespace QueryHelpInterface
{
/// <summary>
/// 获取键盘操作的接口
/// </summary>
public interface IKeyboardOperation : IDisposable
{ /// <summary>
/// 按下或松开按键时发生
/// </summary>
event KeyOperationEventHandler KeyOperation; }//end IKeyBoardOperation
public delegate void KeyOperationEventHandler(object sender, KeyOperationEventArgs e); /// <summary>
/// 按下或松开按键的事件信息
/// </summary>
public class KeyOperationEventArgs : EventArgs
{ /// <summary>
/// 按下或松开按键的事件信息
/// </summary>
/// <param name="keyType">按下或松开按键</param>
/// <param name="keyCode">按键码,表示按下了哪个键</param>
public KeyOperationEventArgs(KeyOperationType keyType, int keyCode)
{
type = keyType;
code = keyCode;
} /// <summary>
/// 获取按键操作是松开按键还是按下按键
/// </summary>
private KeyOperationType type; /// <summary>
/// 按键码,表示按下了哪个按键
/// </summary>
private int code; /// <summary>
/// 获取按键操作是松开按键还是按下按键
/// </summary>
public KeyOperationType KeyType
{
get
{
return type;
}
} /// <summary>
/// 按键码,表示按下了哪个按键
/// </summary>
public int Code
{
get
{
return code;
}
} /// <summary>
/// 获取或设置是否将按键消息传递给下一个队列,默认不传递。
/// </summary>
public bool IsCallNext
{
get;
set;
}
} /// <summary>
/// 按键操作枚举
/// </summary>
public enum KeyOperationType
{ 按下按键,
松开按键,
其他
}
}
1.可以截获按下或松开的按键(无论焦点是否在程序主窗体上)
2.截获按键时应可以获得一些信息,包括:按键的值,按下还是松开按键,是否将按下键操作传递给消息链的下一个对象。
接口已经写好了,只要就行了。实现时可以用任何语言,不论是C#还是C++或是使用其他dll文件,只要我能拿来用就行了(我使用的是C#)。
如果已完成可以上传到网上,给出下载链接就行,往大家予以帮助。PS:我用C#写的全局钩子不打完善,虽然可以截获到按键信息,但是顺序太靠后了,例如在文本框中输入“a”,我能截获到但是如果拦截输入,文本框仍然会输入“a”,使用语句“return 0;”也不行。接口声明如下:namespace QueryHelpInterface
{
/// <summary>
/// 获取键盘操作的接口
/// </summary>
public interface IKeyboardOperation : IDisposable
{ /// <summary>
/// 按下或松开按键时发生
/// </summary>
event KeyOperationEventHandler KeyOperation; }//end IKeyBoardOperation
public delegate void KeyOperationEventHandler(object sender, KeyOperationEventArgs e); /// <summary>
/// 按下或松开按键的事件信息
/// </summary>
public class KeyOperationEventArgs : EventArgs
{ /// <summary>
/// 按下或松开按键的事件信息
/// </summary>
/// <param name="keyType">按下或松开按键</param>
/// <param name="keyCode">按键码,表示按下了哪个键</param>
public KeyOperationEventArgs(KeyOperationType keyType, int keyCode)
{
type = keyType;
code = keyCode;
} /// <summary>
/// 获取按键操作是松开按键还是按下按键
/// </summary>
private KeyOperationType type; /// <summary>
/// 按键码,表示按下了哪个按键
/// </summary>
private int code; /// <summary>
/// 获取按键操作是松开按键还是按下按键
/// </summary>
public KeyOperationType KeyType
{
get
{
return type;
}
} /// <summary>
/// 按键码,表示按下了哪个按键
/// </summary>
public int Code
{
get
{
return code;
}
} /// <summary>
/// 获取或设置是否将按键消息传递给下一个队列,默认不传递。
/// </summary>
public bool IsCallNext
{
get;
set;
}
} /// <summary>
/// 按键操作枚举
/// </summary>
public enum KeyOperationType
{ 按下按键,
松开按键,
其他
}
}
打个比方,如果我是数据库管理人员,我经常会用到一些Sql语句,我希望自己设定一个快捷键,比如Ctrl+1后,向里面输入select * from XXX之类或是其他之类的操作。
C++程序倒是见过,你去VC区问问吧
public class UserActivityHook2
{
#region Windows structure definitions
[StructLayout(LayoutKind.Sequential)]
private class POINT
{
public int x;
public int y;
}
[StructLayout(LayoutKind.Sequential)]
private class MouseHookStruct
{
public POINT pt;
public int hwnd;
public int wHitTestCode;
public int dwExtraInfo;
}
[StructLayout(LayoutKind.Sequential)]
private class MouseLLHookStruct
{
public POINT pt;
public int mouseData;
public int flags;
public int time;
public int dwExtraInfo;
}
[StructLayout(LayoutKind.Sequential)]
private class KeyboardHookStruct
{
public int vkCode;
public int scanCode;
public int flags;
public int time;
public int dwExtraInfo;
}
#endregion #region Windows function imports
[DllImport("user32.dll", CharSet = CharSet.Auto, EntryPoint = "FindWindow")]
public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
[DllImport("user32.dll ", CharSet = CharSet.Auto, ExactSpelling = true)]
public static extern bool EnableWindow(IntPtr hWnd, bool enable);
[DllImport("user32.dll", CharSet = CharSet.Auto,
CallingConvention = CallingConvention.StdCall, SetLastError = true)]
public static extern int SetWindowsHookEx(
int idHook,
HookProc lpfn,
IntPtr hMod,
int dwThreadId);
[DllImport("user32.dll", CharSet = CharSet.Auto,
CallingConvention = CallingConvention.StdCall, SetLastError = true)]
public static extern int UnhookWindowsHookEx(int idHook);
[DllImport("user32.dll", CharSet = CharSet.Auto,
CallingConvention = CallingConvention.StdCall)]
public static extern int CallNextHookEx(
int idHook,
int nCode,
int wParam,
IntPtr lParam); public delegate int HookProc(int nCode, int wParam, IntPtr lParam);
[DllImport("user32")]
private static extern int ToAscii(
int uVirtKey,
int uScanCode,
byte[] lpbKeyState,
byte[] lpwTransKey,
int fuState); [DllImport("user32")]
private static extern int GetKeyboardState(byte[] pbKeyState); [DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
private static extern short GetKeyState(int vKey);
[DllImport("User32.dll", CharSet = CharSet.Auto)]
public static extern int GetWindowThreadProcessId(IntPtr hwnd, int ID); #endregion #region Windows constants private const int WH_MOUSE_LL = 14;
private const int WH_KEYBOARD_LL = 13;
private const int WH_MOUSE = 7;
private const int WH_KEYBOARD = 2;
private const int WM_MOUSEMOVE = 0x200;
private const int WM_LBUTTONDOWN = 0x201;
private const int WM_RBUTTONDOWN = 0x204;
private const int WM_MBUTTONDOWN = 0x207;
private const int WM_LBUTTONUP = 0x202;
private const int WM_RBUTTONUP = 0x205;
private const int WM_MBUTTONUP = 0x208;
private const int WM_LBUTTONDBLCLK = 0x203;
private const int WM_RBUTTONDBLCLK = 0x206;
private const int WM_MBUTTONDBLCLK = 0x209;
private const int WM_MOUSEWHEEL = 0x020A;
private const int WM_KEYDOWN = 0x100;
private const int WM_KEYUP = 0x101;
private const int WM_SYSKEYDOWN = 0x104;
private const int WM_SYSKEYUP = 0x105;
private const byte VK_SHIFT = 0x10;
private const byte VK_CAPITAL = 0x14;
private const byte VK_NUMLOCK = 0x90;
private const byte VK_TAB = 0x09;
private const byte LLKHF_ALTDOWN = 0x20;
private const byte VK_ESCAPE = 0x1B;
private const byte VK_LCONTROL = 0xA2;
private const byte VK_RCONTROL = 0xA3;
private const byte VK_F4 = 0x73; #endregion public UserActivityHook2()
{
Start();
} public UserActivityHook2(bool InstallMouseHook, bool InstallKeyboardHook)
{
Start(InstallMouseHook, InstallKeyboardHook);
} ~UserActivityHook2()
{
//uninstall hooks and do not throw exceptions
Stop(true, true, false);
}
public event MouseEventHandler OnMouseActivity;
public event KeyEventHandler KeyDown;
public event KeyPressEventHandler KeyPress;
public event KeyEventHandler KeyUp;
private int hMouseHook = 0;
private int hKeyboardHook = 0;
private static HookProc MouseHookProcedure;
private static HookProc KeyboardHookProcedure;
public void Start()
{
this.Start(true, true);
}
private void EnableTrayBar(bool b)
{
IntPtr wnd = FindWindow("Shell_traywnd", null);
EnableWindow(wnd, b);
}
public void Start(bool InstallMouseHook, bool InstallKeyboardHook)
{
//disable shell tray bar
EnableTrayBar(false);
// install Mouse hook only if it is not installed and must be installed
if (hMouseHook == 0 && InstallMouseHook)
{
// Create an instance of HookProc.
MouseHookProcedure = new HookProc(MouseHookProc);
[code]
hMouseHook = SetWindowsHookEx(
WH_MOUSE_LL,
MouseHookProcedure,
Marshal.GetHINSTANCE(
Assembly.GetExecutingAssembly().GetModules()[0]),
0);
//If SetWindowsHookEx fails.
if (hMouseHook == 0)
{
//Returns the error code returned by the last unmanaged function called using platform invoke that has the DllImportAttribute.SetLastError flag set.
int errorCode = Marshal.GetLastWin32Error();
//do cleanup
Stop(true, false, false);
//Initializes and throws a new instance of the Win32Exception class with the specified error.
throw new Win32Exception(errorCode);
}
} // install Keyboard hook only if it is not installed and must be installed
if (hKeyboardHook == 0 && InstallKeyboardHook)
{
// Create an instance of HookProc.
KeyboardHookProcedure = new HookProc(KeyboardHookProc);
//install hook
hKeyboardHook = SetWindowsHookEx(
WH_KEYBOARD_LL,
KeyboardHookProcedure,
Marshal.GetHINSTANCE(
Assembly.GetExecutingAssembly().GetModules()[0]),
0);
//If SetWindowsHookEx fails.
if (hKeyboardHook == 0)
{
//Returns the error code returned by the last unmanaged function called using platform invoke that has the DllImportAttribute.SetLastError flag set.
int errorCode = Marshal.GetLastWin32Error();
//do cleanup
Stop(false, true, false);
//Initializes and throws a new instance of the Win32Exception class with the specified error.
throw new Win32Exception(errorCode);
}
}
}
public void Stop()
{
this.Stop(true, true, true);
} public void Stop(bool UninstallMouseHook, bool UninstallKeyboardHook, bool ThrowExceptions)
{
//enable shell tray bar
EnableTrayBar(true);
//if mouse hook set and must be uninstalled
if (hMouseHook != 0 && UninstallMouseHook)
{
//uninstall hook
int retMouse = UnhookWindowsHookEx(hMouseHook);
//reset invalid handle
hMouseHook = 0;
//if failed and exception must be thrown
if (retMouse == 0 && ThrowExceptions)
{
//Returns the error code returned by the last unmanaged function called using platform invoke that has the DllImportAttribute.SetLastError flag set.
int errorCode = Marshal.GetLastWin32Error();
//Initializes and throws a new instance of the Win32Exception class with the specified error.
throw new Win32Exception(errorCode);
}
} //if keyboard hook set and must be uninstalled
if (hKeyboardHook != 0 && UninstallKeyboardHook)
{
//uninstall hook
int retKeyboard = UnhookWindowsHookEx(hKeyboardHook);
//reset invalid handle
hKeyboardHook = 0;
//if failed and exception must be thrown
if (retKeyboard == 0 && ThrowExceptions)
{
//Returns the error code returned by the last unmanaged function called using platform invoke that has the DllImportAttribute.SetLastError flag set.
int errorCode = Marshal.GetLastWin32Error();
//Initializes and throws a new instance of the Win32Exception class with the specified error.
throw new Win32Exception(errorCode);
}
}
}
private int MouseHookProc(int nCode, int wParam, IntPtr lParam)
{
// if ok and someone listens to our events
//bool Disable = false;
if ((nCode >= 0) && (OnMouseActivity != null))
{
//Marshall the data from callback.
MouseLLHookStruct mouseHookStruct = (MouseLLHookStruct)Marshal.PtrToStructure(lParam, typeof(MouseLLHookStruct)); //detect button clicked
MouseButtons button = MouseButtons.None;
short mouseDelta = 0;
switch (wParam)
{
case WM_LBUTTONDOWN:
//case WM_LBUTTONUP:
//case WM_LBUTTONDBLCLK:
button = MouseButtons.Left;
break;
case WM_RBUTTONDOWN:
//case WM_RBUTTONUP:
//case WM_RBUTTONDBLCLK:
button = MouseButtons.Right;
//Disable = true;
break;
case WM_MOUSEWHEEL:
mouseDelta = (short)((mouseHookStruct.mouseData >> 16) & 0xffff);
break;
} //double clicks
int clickCount = 0;
if (button != MouseButtons.None)
if (wParam == WM_LBUTTONDBLCLK || wParam == WM_RBUTTONDBLCLK) clickCount = 2;
else clickCount = 1; //generate event
MouseEventArgs e = new MouseEventArgs(
button,
clickCount,
mouseHookStruct.pt.x,
mouseHookStruct.pt.y,
mouseDelta);
//raise it
OnMouseActivity(this, e);
}
//call next hook
return CallNextHookEx(hMouseHook, nCode, wParam, lParam);
}
private int KeyboardHookProc(int nCode, Int32 wParam, IntPtr lParam)
{
//indicates if any of underlaing events set e.Handled flag
bool handled = false;
//it was ok and someone listens to events
if ((nCode >= 0) && (KeyDown != null || KeyUp != null || KeyPress != null))
{
//read structure KeyboardHookStruct at lParam
KeyboardHookStruct MyKeyboardHookStruct = (KeyboardHookStruct)Marshal.PtrToStructure(lParam, typeof(KeyboardHookStruct));
if (((Keys)MyKeyboardHookStruct.vkCode == Keys.LWin) || ((Keys)MyKeyboardHookStruct.vkCode == Keys.RWin) ||
((MyKeyboardHookStruct.vkCode == VK_TAB) && ((MyKeyboardHookStruct.flags & LLKHF_ALTDOWN) != 0)) ||
((MyKeyboardHookStruct.vkCode == VK_ESCAPE) && ((MyKeyboardHookStruct.flags & LLKHF_ALTDOWN) != 0)) ||
((MyKeyboardHookStruct.vkCode == VK_F4) && ((MyKeyboardHookStruct.flags & LLKHF_ALTDOWN) != 0)) ||
(MyKeyboardHookStruct.vkCode == VK_ESCAPE) && ((GetKeyState(VK_LCONTROL) & 0x8000) != 0) ||
(MyKeyboardHookStruct.vkCode == VK_ESCAPE) && ((GetKeyState(VK_RCONTROL) & 0x8000) != 0)
)
{
handled = true;
}
}
//if event handled in application do not handoff to other listeners
if (handled)
return 1;
else
return CallNextHookEx(hKeyboardHook, nCode, wParam, lParam);
}
}
[DllImport("user32")]
public static extern bool RegisterHotKey(IntPtr hWnd, int id, uint control, Keys vk);
//注册热键的api
[DllImport("user32")]
public static extern bool UnregisterHotKey(IntPtr hWnd, int id);
void FlashWin_FormClosed(object sender, FormClosedEventArgs e)
{
//注消热键(句柄,热键ID)
UnregisterHotKey(this.Handle, 1000);
} private void FlashWin_Load(object sender, EventArgs e)
{
//注册热键(窗体句柄,热键ID,辅助键,实键)
RegisterHotKey(this.Handle, 888, 2, Keys.A); //2是Cltr
} protected override void WndProc(ref Message m)
{
switch (m.Msg)
{
case 0x0312: //这个是window消息定义的 注册的热键消息
if (m.WParam.ToString().Equals("1000")) //如果是我们注册的那个热键
MessageBox.Show("你按了ctrl+a");
break;
}
base.WndProc(ref m);
}