-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathShortcuts.cs
More file actions
72 lines (62 loc) · 2.16 KB
/
Shortcuts.cs
File metadata and controls
72 lines (62 loc) · 2.16 KB
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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Interop;
namespace PlayNextSong
{
public class Shortcuts
{
private IList<IKeyboardShortcutCommand> _shortcuts = new List<IKeyboardShortcutCommand>();
private int WM_HOTKEY = 0x0312;
private IntPtr windowHook = IntPtr.Zero;
private HwndSource _source = null;
public void AddShortcut(IKeyboardShortcutCommand shortcut)
{
_shortcuts.Add(shortcut);
}
public void RemoveShortcut(IKeyboardShortcutCommand shortcut)
{
var toRemove = _shortcuts.FirstOrDefault(i => i.Id == shortcut.Id);
if (toRemove != null)
{
_shortcuts.Remove(toRemove);
}
}
public void Register(IntPtr windowHandle)
{
windowHook = windowHandle;
_source = HwndSource.FromHwnd(windowHook);
_source.AddHook(HwndHook);
for (int i = 0; i < _shortcuts.Count; i++)
{
if (!NativeMethods.RegisterHotKey(windowHook, _shortcuts[i].Id,
_shortcuts[i].Modifiers,
_shortcuts[i].VirtualKey))
{
throw new Exception(message: string.Format("Unable to register hotkey. Modifiers: {0}, VK: {1}", _shortcuts[i].Modifiers, _shortcuts[i].VirtualKey));
}
}
}
private IntPtr HwndHook(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
{
if (msg == WM_HOTKEY)
{
var unInitialized = _shortcuts.Where(x => x.InvokePattern == null);
foreach (var command in unInitialized)
{
command.Initialize();
}
var matched = _shortcuts.Where(x => x.Id == wParam.ToInt32()).ToList();
foreach (var command in matched)
{
command.Invoke();
}
}
return IntPtr.Zero;
}
public void Dispose()
{
_shortcuts.Clear();
}
}
}