我正在为游戏制作一些工具,计算在发生事情之前还剩多少时间。 当F1按下时,它就开始算了。
如何检测F1是否被按下?当然,该计划将被最小化。 我正在使用C#,winform。
答案 0 :(得分:0)
我使用以下方法在键盘中禁用我的Rwin和Lwin。我修改了一下它可能对你有用。事情基本上是F1用于Windows中的帮助,因此您必须首先禁用默认功能。看看:
// Structure contain information about low-level keyboard input event
[StructLayout(LayoutKind.Sequential)]
private struct KBDLLHOOKSTRUCT
{
public Keys key;
public int scanCode;
public int flags;
public int time;
public IntPtr extra;
}
//System level functions to be used for hook and unhook keyboard input
private delegate IntPtr LowLevelKeyboardProc(int nCode, IntPtr wParam, IntPtr lParam);
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern IntPtr SetWindowsHookEx(int id, LowLevelKeyboardProc callback, IntPtr hMod, uint dwThreadId);
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern bool UnhookWindowsHookEx(IntPtr hook);
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern IntPtr CallNextHookEx(IntPtr hook, int nCode, IntPtr wp, IntPtr lp);
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern IntPtr GetModuleHandle(string name);
[DllImport("user32.dll", CharSet = CharSet.Auto)]
private static extern short GetAsyncKeyState(Keys key);
//Declaring Global objects
private IntPtr ptrHook;
private LowLevelKeyboardProc objKeyboardProcess;
private IntPtr CaptureKey(int nCode, IntPtr wp, IntPtr lp)
{
if (nCode >= 0)
{
KBDLLHOOKSTRUCT objKeyInfo = (KBDLLHOOKSTRUCT)Marshal.PtrToStructure(lp, typeof(KBDLLHOOKSTRUCT));
if (objKeyInfo.key == Keys.F1) // Disabling Windows keys
{
MessageBox.Show("F1 PRESSED");
return (IntPtr)1;
}
}
return CallNextHookEx(ptrHook, nCode, wp, lp);
}
public Form1()
{
InitializeComponent();
this.WindowState = FormWindowState.Minimized;
//Get Current Module
ProcessModule objCurrentModule = Process.GetCurrentProcess().MainModule;
//Assign callback function each time keyboard process
objKeyboardProcess = new LowLevelKeyboardProc(CaptureKey);
//Setting Hook of Keyboard Process for current module
ptrHook = SetWindowsHookEx(13, objKeyboardProcess, GetModuleHandle(objCurrentModule.ModuleName), 0);
}
注意:您必须使用以下命名空间:
using System.Diagnostics;
using System.Runtime.InteropServices;