在游戏中按下一个键,我的程序会点击'Start'

本文关键字:Start 程序 我的 游戏 下一个 | 更新日期: 2023-09-27 17:49:51

我目前正在做一个程序,它将宣布和倒计时从例子中让我们说5分钟,所以当你按开始按钮它将从5分钟倒数到0,

我想要的东西是:

如果我正在玩全屏游戏,例如《魔兽世界》、《英雄联盟》或任何具有全屏图像的游戏,并且我按下了Numpad 8,我希望程序在按钮1上点击开始。

这应该是可能的,因为我以前见过它,但我不知道怎么做

在游戏中按下一个键,我的程序会点击'Start'

我在《英雄联盟》和《Terraria》上进行了测试。以下作品:

public static class WindowsAPI
{
    public enum HookType : int
    {
        WH_JOURNALRECORD = 0,
        WH_JOURNALPLAYBACK = 1,
        WH_KEYBOARD = 2,
        WH_GETMESSAGE = 3,
        WH_CALLWNDPROC = 4,
        WH_CBT = 5,
        WH_SYSMSGFILTER = 6,
        WH_MOUSE = 7,
        WH_HARDWARE = 8,
        WH_DEBUG = 9,
        WH_SHELL = 10,
        WH_FOREGROUNDIDLE = 11,
        WH_CALLWNDPROCRET = 12,
        WH_KEYBOARD_LL = 13,
        WH_MOUSE_LL = 14
    }
    [StructLayout(LayoutKind.Sequential)]
    public struct KeyboardHookStruct
    {
        public int VirtualKeyCode;
        public int ScanCode;
        public int Flags;
        public int Time;
        public int ExtraInfo;
    }
    public delegate IntPtr HookProc(int nCode, IntPtr wp, IntPtr lp);
    [DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
    public static extern IntPtr SetWindowsHookEx(HookType idHook, HookProc lpfn, IntPtr hInstance, uint threadId);
    [DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
    public static extern bool UnhookWindowsHookEx(IntPtr hHook);
    [DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
    public static extern IntPtr CallNextHookEx(HookType idHook, int nCode, IntPtr wParam, IntPtr lParam);
}

然后"hook"它:

public partial class Form1 : Form
{
    private IntPtr kbhook = IntPtr.Zero;
    private void Form1_Load(object sender, EventArgs e)
    {
        kbhook = WindowsAPI.SetWindowsHookEx(WindowsAPI.HookType.WH_KEYBOARD_LL, HandleKeyPress, IntPtr.Zero, 0);
        if (kbhook == IntPtr.Zero)
            Application.Exit();
    }
    private void Form1_FormClosing(object sender, FormClosingEventArgs e)
    {
        WindowsAPI.UnhookWindowsHookEx(kbhook);
    }

    private IntPtr HandleKeyPress(int nCode, IntPtr wp, IntPtr lp)
    {
        WindowsAPI.KeyboardHookStruct MyKeyboardHookStruct =
            (WindowsAPI.KeyboardHookStruct)Marshal.PtrToStructure(lp, typeof(WindowsAPI.KeyboardHookStruct));
        var key = (Keys)MyKeyboardHookStruct.VirtualKeyCode;
        // **********************************
        // if the pressed key is Keys.NumPad8
        if (key == Keys.NumPad8)
        {
            button1_Click(null, EventArgs.Empty);
        }
        return WindowsAPI.CallNextHookEx(WindowsAPI.HookType.WH_KEYBOARD_LL, nCode, wp, lp);
    }
}

pinvoke.net可能有过时的代码示例,但它有助于了解方法签名