gpt4 book ai didi

c# - 从任何进程获取 key

转载 作者:行者123 更新时间:2023-11-30 19:18:05 25 4
gpt4 key购买 nike

我在网上看到了很多解决方案,但没有一个完全符合我的要求。当我的应用程序在后台运行时,在给定进程(不是我的控制台应用程序)中按下任何键的最佳/最简单方法是什么。我不需要修饰符或任何东西。

最佳答案

如果您不特别关心按键被按下的过程,最简单的方法是调用 GetAsyncKeyState .它相当有限,因为它不会挂接键盘并且需要您连续调用它。我认为最好的方法是挂接键盘。

使用 SetWindowsHookEx您实际上可以明确指定与 Hook 过程相关联的线程的标识符,以便您可以 Hook 特定进程的键(请参阅 dwThreadId)。

这是一个你可以使用的类(最初是在 Micrsoft 博客上找到的,但我现在似乎找不到作者的名字!)

public delegate IntPtr KeyboardProcess(int nCode, IntPtr wParam, IntPtr lParam);

public sealed class KeyboardHook
{
public static event EventHandler<KeyPressedEventArgs> KeyPressed;
private const int WH_KEYBOARD = 13;
private const int WM_KEYDOWN = 0x0100;
private static KeyboardProcess keyboardProc = HookCallback;
private static IntPtr hookID = IntPtr.Zero;

public static void CreateHook()
{
hookID = SetHook(keyboardProc);
}

public static void DisposeHook()
{
UnhookWindowsHookEx(hookID);
}

private static IntPtr SetHook(KeyboardProcess keyboardProc)
{
using (Process currentProcess = Process.GetCurrentProcess())
using (ProcessModule currentProcessModule = currentProcess.MainModule)
{
return SetWindowsHookEx(WH_KEYBOARD, keyboardProc, GetModuleHandle(currentProcessModule.ModuleName), 0);
}
}

private static IntPtr HookCallback(int nCode, IntPtr wParam, IntPtr lParam)
{
if (nCode >= 0 && wParam == (IntPtr)WM_KEYDOWN)
{
int vkCode = Marshal.ReadInt32(lParam);

if (KeyPressed != null)
KeyPressed(null, new KeyPressedEventArgs((Keys)vkCode));
}
return CallNextHookEx(hookID, nCode, wParam, lParam);
}

[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern IntPtr SetWindowsHookEx(int idHook, KeyboardProcess lpfn, IntPtr hMod, uint dwThreadId);

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

[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool UnhookWindowsHookEx(IntPtr hhk);

}

public class KeyPressedEventArgs : EventArgs
{
public Keys KeyCode { get; set; }
public KeyPressedEventArgs(Keys Key)
{
KeyCode = Key;
}
}

通过控制台应用程序实现:

class Program
{
static void Main(string[] args)
{
KeyboardHook.CreateHook();
KeyboardHook.KeyPressed += KeyboardHook_KeyPressed;
Application.Run();
KeyboardHook.DisposeHook();
}

static void KeyboardHook_KeyPressed(object sender, KeyPressedEventArgs e)
{
Console.WriteLine(e.KeyCode.ToString());
}
}

关于c# - 从任何进程获取 key ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13998131/

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