-
Notifications
You must be signed in to change notification settings - Fork 0
/
HotKeyWindow.cs
executable file
·67 lines (55 loc) · 1.86 KB
/
HotKeyWindow.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
// <copyright file="HotKeyWindow.cs">
// CopyCopyDict - Background app that opens a dictionary definition of a selected word by Ctrl+C+C
// (c) 2023 Artem Avramenko. https://github.com/ArtemAvramenko/CopyCopyDict
// License: MIT
// </copyright>
using System;
using System.Runtime.InteropServices;
using System.Windows.Forms;
namespace CopyCopyDict
{
internal class HotKeyWindow : NativeWindow
{
private const int WM_HOTKEY = 0x312;
private const int HotKeyId = 1;
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern bool RegisterHotKey(IntPtr hWnd, int id, KeyModifiers fsModifiers, Keys vk);
[DllImport("user32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool UnregisterHotKey(IntPtr hWnd, int id);
public HotKeyWindow()
{
CreateHandle(new CreateParams());
}
public event MethodInvoker Pressed;
private bool _isRegistered;
protected override void WndProc(ref Message m)
{
if (m.Msg == WM_HOTKEY &&
_isRegistered &&
m.WParam.ToInt32() == HotKeyId &&
Pressed != null)
{
Pressed();
}
base.WndProc(ref m);
}
public void Register(KeyModifiers modifiers, Keys key)
{
if (_isRegistered)
{
Unregister();
}
RegisterHotKey(Handle, HotKeyId, modifiers, key);
_isRegistered = true;
}
public void Unregister()
{
if (_isRegistered)
{
UnregisterHotKey(Handle, HotKeyId);
_isRegistered = false;
}
}
}
}