-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathKeyListener.cs
88 lines (76 loc) · 2.35 KB
/
KeyListener.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
using System;
using System.Collections.Generic;
using System.Linq;
using System.Diagnostics;
using System.Windows.Input;
using System.Threading;
using System.Threading.Tasks;
using static KeyBinder.MainWindow;
namespace KeyBinder
{
class KeyListener
{
private static HashSet<Key> pressedKeys = new HashSet<Key>();
private static bool isEnabled = true;
private static readonly Object lockIt = new object();
HotkeyProcessor processor;
CancellationToken token;
public KeyListener(CancellationToken token, ViewModel viewModel, CallbackNotifyUser notifyUser)
{
processor = new HotkeyProcessor(token, viewModel, notifyUser);
this.token = token;
}
public static void disableKeyListener()
{
lock (lockIt)
{
isEnabled = false;
}
}
public static void enableKeyListener()
{
lock (lockIt)
{
isEnabled = true;
}
}
/// <summary>
/// Starts infinite run of the keylogger
/// </summary>
public async void StartMonitorAsync()
{
Console.WriteLine("Initializing monitor...");
DataSource dataSource = new DataSource();
Task.Run(() => processor.StartProcessorAsync());
while (true && !token.IsCancellationRequested)
{
if (isEnabled)
{
try
{
pressedKeys = dataSource.GetPressedKeys();
}
catch (Exception e)
{
Console.WriteLine(e.Message);
Console.WriteLine("Closing thread KeyListener...");
return;
}
if (pressedKeys.Any())
{
processKeys(pressedKeys);
}
}
Thread.Sleep(50);
}
Console.WriteLine("Closing thread KeyListener...");
}
public void processKeys(HashSet<Key> pressedKeys)
{
if (pressedKeys.Count > 1)
{
processor.addHotkey(Utils.converKeysToHotkeyString(pressedKeys));
}
}
}
}