SafeDispatch/SafeMobileLIB_DLL/KeyInterceptor/KeyInterceptor.cs

96 lines
3.3 KiB
C#
Raw Permalink Normal View History

2024-02-22 16:43:59 +00:00
using System;
using System.Collections.Generic;
using System.Windows.Forms;
namespace SafeMobileLib
{
public class KeyInterceptor
{
private GlobalKeyboardHook _globalKeyboardHook;
private EventHandler<GlobalKeyboardHookEventArgs> callbackKeyboardHook;
public enum KeyState { UP, DOWN, UNKNOWN};
private Dictionary<int, KeyState> keyStates;
private enum TriggerState { TRIGGERED, NOT_TRIGGERED };
private TriggerState triggeredState = TriggerState.NOT_TRIGGERED;
private Keys searchedKey;
private Keys specialKey;
private int specKey = 164;
private int searKey = 65;
public KeyInterceptor(Keys searchedKey, Keys specialKey)
{
keyStates = new Dictionary<int, KeyState>();
this.searchedKey = searchedKey;
this.specialKey = specialKey;
searKey = (int)searchedKey;
specKey = specialKey == Keys.Alt ? 164 : (specialKey == Keys.ShiftKey ? 160 : 162);
keyStates.Add(searKey, KeyState.UNKNOWN);
keyStates.Add(specKey, KeyState.UNKNOWN);
keyStates.Add(0x73, KeyState.UNKNOWN);
_globalKeyboardHook = new GlobalKeyboardHook();
callbackKeyboardHook = new EventHandler<GlobalKeyboardHookEventArgs>(OnKeyPressed);
_globalKeyboardHook.KeyboardPressed += callbackKeyboardHook;
}
private void OnKeyPressed(object sender, GlobalKeyboardHookEventArgs e)
{
if (!keyStates.ContainsKey(e.KeyboardData.VirtualCode))
keyStates.Add(e.KeyboardData.VirtualCode, KeyState.UNKNOWN);
keyStates[e.KeyboardData.VirtualCode] = (e.KeyboardState.ToString().ToLower().Contains("down") ? KeyState.DOWN : KeyState.UP);
if (keyStates[164] == KeyState.DOWN && keyStates[0x73] == KeyState.DOWN)
{
Utils.WriteLine("Alt+F4 pressed", ConsoleColor.Green);
}
if (keyStates[specKey] == KeyState.DOWN && keyStates[searKey] == KeyState.DOWN)
{
if (triggeredState == TriggerState.NOT_TRIGGERED)
{
OnKeyPressedStateChanged?.Invoke((Keys)searKey, specKey == 164 ? Keys.Alt : (specKey == 160 ? Keys.ShiftKey : Keys.ControlKey), KeyState.DOWN);
triggeredState = TriggerState.TRIGGERED;
}
}
else
{
if (triggeredState == TriggerState.TRIGGERED)
{
OnKeyPressedStateChanged?.Invoke((Keys)searKey, specKey == 164 ? Keys.Alt : (specKey == 160 ? Keys.ShiftKey : Keys.ControlKey), KeyState.UP);
triggeredState = TriggerState.NOT_TRIGGERED;
}
}
if (e.KeyboardData.VirtualCode != GlobalKeyboardHook.VkSnapshot)
return;
if (e.KeyboardState == GlobalKeyboardHook.KeyboardState.KeyDown)
{
Utils.WriteLine("Print Screen", ConsoleColor.Red);
e.Handled = true;
}
}
public void Dispose()
{
_globalKeyboardHook?.Dispose();
}
public delegate void KeyStateChanged(Keys searchedKEy, Keys specialKey, KeyState state);
public event KeyStateChanged OnKeyPressedStateChanged;
}
}