如何计算 C# 应用程序中在整个屏幕上按下的总键数?就像应用程序在后面运行并且我正在打字一样......然后我可以看到我按下了多少个键。谢谢你。
问问题
3957 次
5 回答
24
在MSDN 博客上找到:
成立:
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
_hookID = SetHook(_proc);
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
UnhookWindowsHookEx(_hookID);
}
private const int WH_KEYBOARD_LL = 13;
private const int WM_KEYDOWN = 0x0100;
private static LowLevelKeyboardProc _proc = HookCallback;
private static IntPtr _hookID = IntPtr.Zero;
private static IntPtr SetHook(LowLevelKeyboardProc proc)
{
using (Process curProcess = Process.GetCurrentProcess())
using (ProcessModule curModule = curProcess.MainModule)
{
return SetWindowsHookEx(WH_KEYBOARD_LL, proc,
GetModuleHandle(curModule.ModuleName), 0);
}
}
private delegate IntPtr LowLevelKeyboardProc(
int nCode, IntPtr wParam, IntPtr lParam);
private static IntPtr HookCallback(
int nCode, IntPtr wParam, IntPtr lParam)
{
if (nCode >= 0 && wParam == (IntPtr)WM_KEYDOWN)
{
int vkCode = Marshal.ReadInt32(lParam);
Console.WriteLine((Keys)vkCode);
}
return CallNextHookEx(_hookID, nCode, wParam, lParam);
}
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern IntPtr SetWindowsHookEx(int idHook,
LowLevelKeyboardProc lpfn, IntPtr hMod, uint dwThreadId);
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool UnhookWindowsHookEx(IntPtr hhk);
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern IntPtr CallNextHookEx(IntPtr hhk, int nCode,
IntPtr wParam, IntPtr lParam);
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern IntPtr GetModuleHandle(string lpModuleName);
}
于 2012-08-03T11:12:09.713 回答
1
我会解决您的应用程序运行落后的原因(将代码移动到后台工作人员?)
如果您在这样做之后仍然想要全局 keypresscount,请查看这个在 C# 中挂钩 keypress 应用程序范围的演示项目
http://www.codeproject.com/Articles/19004/A-Simple-C-Global-Low-Level-Keyboard-Hook
于 2012-08-14T13:45:10.900 回答
0
于 2012-08-16T07:29:40.273 回答
0
也许它会给你一些想法:
private void OnKeyDownHandler(object sender, KeyEventArgs e)
{
if (e.Key == Key.Return)
{
textBlock1.Text = "You Entered: " + textBox1.Text;
}
}
于 2012-08-15T15:08:13.377 回答
0
我使用如下所示的ProcessKeyEventArgs来捕获Print Screen
我的 C# Windows 窗体中的按键。
我所做的修改就是添加一个计数器并增加它。
private long counter = 0;
protected override bool ProcessKeyEventArgs(ref Message msg) {
counter++;
return base.ProcessKeyEventArgs(ref msg);
}
于 2012-08-16T19:21:32.990 回答