在游戏中按一个键,这将使我的程序点击“开始”

时间:2011-04-11 18:51:10

标签: c# keyboard fullscreen

我目前正在执行一个程序,该程序将通过示例发布和倒计时让我们说5分钟,所以当您按开始按钮时,它将从5分钟倒计时到0,

我想拥有的是:

如果我在全屏游戏中,例如魔兽世界,英雄联盟或任何带全屏图形的游戏,我按 Numpad 8 ,我希望程序点击开始在按钮1

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

1 个答案:

答案 0 :(得分:0)

我在英雄联盟和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);
}

然后“勾起”它:

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可能已过时的代码示例,但有助于了解方法签名。