用C#做键盘敲击次数记录求代码
发布网友
发布时间:2023-05-24 16:53
我来回答
共3个回答
热心网友
时间:2024-11-25 07:04
刚好最近学习钩子,以下是整理源码。
static int hKeyboardHook = 0; //键盘钩子句柄
public const int WH_KEYBOARD_LL = 13; //处理键盘消息
private const int WM_KEYDOWN = 0x100;//键盘按下
//声明键盘钩子事件类型.
HookProc KeyboardHookProcere;
//声明键盘钩子的封送结构类型
[StructLayout(LayoutKind.Sequential)]
public class KeyboardHookStruct
{
public int vkCode; //表示一个在1到254间的虚似键盘码
}
//装置钩子的函数
[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("user32")]
public static extern int ToAscii(int uVirtKey, int uScanCode, byte[] lpbKeyState, byte[] lpwTransKey, int fuState);
[DllImport("user32")]
public static extern int GetKeyboardState(byte[] pbKeyState);
[DllImport("kernel32.dll", CharSet = CharSet.Auto,CallingConvention = CallingConvention.StdCall)]
private static extern IntPtr GetMoleHandle(string lpMoleName);
public delegate int HookProc(int nCode, Int32 wParam, IntPtr lParam);
//先前按下的键
public List<Keys> preKeys = new List<Keys>();
int b;
//析构函数.
~Form1()
{
Stop();
}
public void Start()
{
//安装键盘钩子
if (hKeyboardHook == 0)
{
KeyboardHookProcere = new HookProc(KeyboardHookProc);
Process curProcess = Process.GetCurrentProcess();//获取新的 Process 组件并将其与当前活动的进程关联
ProcessMole curMole = curProcess.MainMole;
hKeyboardHook = SetWindowsHookEx(WH_KEYBOARD_LL, KeyboardHookProcere, GetMoleHandle(curMole.MoleName), 0);
if (hKeyboardHook == 0)
{
Stop();
throw new Exception("SetWindowsHookEx ist failed.");
}
b = 0;
}
}
public void Stop()
{
bool retKeyboard = true;
if (hKeyboardHook != 0)
{
retKeyboard = UnhookWindowsHookEx(hKeyboardHook);
hKeyboardHook = 0;
}
//如果卸下钩子失败
if (!(retKeyboard)) throw new Exception("UnhookWindowsHookEx failed.");
}
int num = 0;//记录次数
private int KeyboardHookProc(int nCode, Int32 wParam, IntPtr lParam)
{
if (wParam == WM_KEYDOWN)
{
KeyboardHookStruct MyKeyboardHookStruct = (KeyboardHookStruct)Marshal.PtrToStructure(lParam, typeof(KeyboardHookStruct));
Keys keyData = (Keys)MyKeyboardHookStruct.vkCode;
preKeys.Add(keyData);
num++;
label1.Text = Convert.ToString(num);
b = 1;
}
return CallNextHookEx(hKeyboardHook, nCode, wParam, lParam);
}
private void Form1_Load(object sender, EventArgs e)
{
Start();
}
热心网友
时间:2024-11-25 07:04
对于OnKeyPress的重载是针对你的Form来的,也就是说发往你的Form的KeyPress事件会被截获,而发往其他程序的消息是得不到的
按照你说的,实际上是做的键盘钩子(截获密码用的),这样说就差不多能理解可行性了
另外,就算是键盘钩子,好像也仅能针对某一个进程,貌似不能针对整个系统
个人观点 坐等高人
热心网友
时间:2024-11-25 07:05
我只能给你个提示-----全局钩子 要想在任何窗体下点击都有记录 需要全局钩子