Skip to content

Instantly share code, notes, and snippets.

@cobrce
Created January 26, 2019 21:41
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 cobrce/55ee56d4abed995ae340e40f8e77f06f to your computer and use it in GitHub Desktop.
Save cobrce/55ee56d4abed995ae340e40f8e77f06f to your computer and use it in GitHub Desktop.
form using RawInput and Hook to block keys from specific device
using RawInput_dll;
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Windows.Forms;
namespace RFID.Redir.lib
{
public partial class HiddenForm : Form
{
RawInput rawinput;
string portName;
Redirector redirector;
public List<int> toRemove = new List<int>();
public event EventHandler NotifyIconDoubleClick;
public HiddenForm()
{
InitializeComponent();
}
public HiddenForm(string portName, Redirector redirector) : this()
{
this.redirector = redirector;
this.portName = portName;
}
private void HiddenForm_Load(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(portName))
{
InitRawInput();
InstallHook(Handle);
}
}
#region Code of redirection based on RawInput
[DllImport("HookingRawInputDemoDLL.dll", CallingConvention = CallingConvention.Cdecl)]
private static extern bool InstallHook(IntPtr hwndParent);
[DllImport("HookingRawInputDemoDLL.dll")]
private static extern bool UninstallHook();
private void InitRawInput()
{
rawinput = new RawInput(Handle, false);
rawinput.AddMessageFilter();
rawinput.KeyPressed += Rawinput_KeyPressed;
}
private void Rawinput_KeyPressed(object sender, RawInputEventArg e)
{
const int WM_KEYDOWN = 0x100;
if (redirector.Redirect(e.KeyPressEvent.DeviceName,
e.KeyPressEvent.VKey,
e.KeyPressEvent.Message == WM_KEYDOWN))
{
toRemove.Add(e.KeyPressEvent.VKey);
}
}
private void HiddenForm_FormClosing(object sender, FormClosingEventArgs e)
{
UninstallHook();
redirector.Dispose();
}
protected override void WndProc(ref Message m)
{
const int WM_APP = 0x8000;
const int WM_HOOK = WM_APP + 1;
base.WndProc(ref m);
switch (m.Msg)
{
case WM_HOOK:
for (int i = 0; i < toRemove.Count; i++)
{
if (toRemove[i] == m.WParam.ToInt32())
{
toRemove.RemoveAt(i);
m.Result = (IntPtr)1;
break;
}
}
break;
}
}
#endregion
private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)
{
NotifyIconDoubleClick?.Invoke(this, e);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment