Skip to content

Instantly share code, notes, and snippets.

@dburriss
Created August 2, 2018 05:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dburriss/6655745100c2c3eacc8eaee7898f097a to your computer and use it in GitHub Desktop.
Save dburriss/6655745100c2c3eacc8eaee7898f097a to your computer and use it in GitHub Desktop.
Console app that listens for keypress events even in the packground
namespace Native
type HookProc = delegate of int * nativeint * nativeint -> nativeint
module User32 =
open System.Runtime.InteropServices
[<DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)>]
extern nativeint SetWindowsHookEx(int idHook, HookProc lpfn, nativeint hMod, uint32 dwThreadId)
[<DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)>]
[<MarshalAs(UnmanagedType.Bool)>]
extern bool UnhookWindowsHookEx(nativeint hhk)
[<DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)>]
extern nativeint CallNextHookEx(nativeint hhk, int nCode, nativeint wParam, nativeint lParam)
module Kernal32 =
open System.Runtime.InteropServices
[<DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)>]
extern nativeint GetModuleHandle(string lpModuleName)
module Program =
open System.Runtime.InteropServices
open System.Windows.Forms
open System.Diagnostics
// Credit: https://blogs.msdn.microsoft.com/toub/2006/05/03/low-level-keyboard-hook-in-c/
[<Literal>]
let WH_KEYBOARD_LL = 13
[<Literal>]
let WM_KEYDOWN = 0x0100
let mutable hookId = nativeint 0
[<EntryPoint>]
let main argv =
let sprintKey k = KeysConverter().ConvertToString(k)
// installs a hook from WH_KEYBOARD_LL events to callback.
// See: https://msdn.microsoft.com/en-us/library/windows/desktop/ms644990(v=vs.85).aspx
let setHook hookProc : nativeint =
using (Process.GetCurrentProcess()) (fun curProcess ->
using (curProcess.MainModule) ( fun curModule ->
let handle = Kernal32.GetModuleHandle(curModule.ModuleName)
User32.SetWindowsHookEx(WH_KEYBOARD_LL, hookProc, handle, (0 |> uint32))
))
let callback = fun nCode wParam lParam ->
if (nCode >= 0 && wParam = (WM_KEYDOWN |> nativeint)) then
let vkCode = Marshal.ReadInt32(lParam)
printfn "%s" (sprintKey vkCode)
User32.CallNextHookEx(hookId, nCode, wParam, lParam)
hookId <- setHook(new HookProc(callback))
Application.Run()
User32.UnhookWindowsHookEx(hookId) |> ignore
0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment