gpt4 book ai didi

最小化时的 C# 击键拦截器

转载 作者:行者123 更新时间:2023-11-30 16:12:12 24 4
gpt4 key购买 nike

好的,所以我正在尝试编写一个程序来跟踪我在玩游戏时的击键,以便我以后可以分析数据以帮助我改进我的游戏。我一直试图做的是使用 user32.dll 的 RegisterHotKey 实现一个全局热键 Hook 。但这完全捕获了击键,并且游戏不再接收击键。我不知道从这里去哪里,任何指示将不胜感激。以下是一些附加信息:

  • 我正在使用 C#
  • .NET 4
  • 使用 Visual Studio 2010
  • 我并没有试图做任何违法的事情,或者违反游戏服务条款

最佳答案

这摘自 Stephan Toubs 2006 年的博客:

http://blogs.msdn.com/b/toub/archive/2006/05/03/589423.aspx

using System.Diagnostics;
using System.Windows.Forms;
using System.Runtime.InteropServices;

class InterceptKeys
{
private const int WH_KEYBOARD_LL = 13;
private const int WM_KEYDOWN = 0x0100;
private static LowLevelKeyboardProc _proc = HookCallback;
private static IntPtr _hookID = IntPtr.Zero;

public static void Main()
{
_hookID = SetHook(_proc);
Application.Run();
UnhookWindowsHookEx(_hookID);
}

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);
}

关于最小化时的 C# 击键拦截器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23286585/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com