I'm making some tool for game, that counting how much time left until something happens. it's start to count when F1 pressed.
How can i detect if F1 was pressed? the program would be minimized of course. I'm using C#, winform.
I'm making some tool for game, that counting how much time left until something happens. it's start to count when F1 pressed.
How can i detect if F1 was pressed? the program would be minimized of course. I'm using C#, winform.
I used below method to disable my Rwin and Lwin in my keyboard. I modified a bit maybe it could be useful for you. The thing is basically F1 is using for the help in the windows so you must disable the default functionality first. Check it out:
// 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);
}
Note: You must use the below namespace:
using System.Diagnostics;
using System.Runtime.InteropServices;