-
Notifications
You must be signed in to change notification settings - Fork 31
/
Program.cs
362 lines (337 loc) · 12.6 KB
/
Program.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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
using Gma.System.MouseKeyHook;
using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Media;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace ClickPaste
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
if(Properties.Settings.Default.RunElevated)
{
}
// only run one of these at a time!
//https://stackoverflow.com/questions/502303/how-do-i-programmatically-get-the-guid-of-an-application-in-net2-0/502323#502323
string assyGuid = Assembly.GetExecutingAssembly().GetCustomAttribute<GuidAttribute>().Value.ToUpper();
bool createdNew;
new System.Threading.Mutex(false, assyGuid, out createdNew);
if (!createdNew) return;
Native.SetProcessDPIAware();
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
// try to make sure we don't die leaving the cursor in "+" state
AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
AppDomain.CurrentDomain.ProcessExit += CurrentDomain_ProcessExit;
Application.Run(new TrayApplicationContext());
}
private static void CurrentDomain_ProcessExit(object sender, EventArgs e)
{
// reset cursors
Native.SystemParametersInfo(0x0057, 0, null, 0);
}
private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
// reset cursors
Native.SystemParametersInfo(0x0057, 0, null, 0);
}
}
public static class Extensions
{
public static uint? RegToUint(this object value) => value == null ? (uint?)null : Convert.ToUInt32(value);
public static string[] Names(this Type enumType) => Enum.GetNames(enumType);
public static int Count(this Type enumType) => enumType.Names().Length;
public static object Value(this Type enumType, string name) => Enum.Parse(enumType, name);
public static string First(this string s, int count)
{
if (count > s.Length) return s;
return s.Substring(0, count);
}
}
public enum TypeMethod
{
Forms_SendKeys = 0,
AutoIt_Send
}
public enum HotKeyMode
{
Target = 0,
JustGo
}
public class TrayApplicationContext : ApplicationContext
{
NotifyIcon _notify = null;
IKeyboardMouseEvents _hook = null;
MenuItem[] _typeMethods; // these are just sequential 0-based integers so don't need to map them like...
Dictionary<int, MenuItem> _keyDelayMS;// we do here
int? _usingHotKey;
EventHandler<HotKeyEventArgs> _currentHotKeyHandler = null;
CancellationTokenSource _stop = new CancellationTokenSource();
bool _settingsOpen = false;
public TrayApplicationContext()
{
StartHotKey();
bool darkTray = true;
using (var key = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Themes\Personalize"))
{
var light = key?.GetValue("SystemUsesLightTheme")?.RegToUint();
if (light.HasValue)
{
darkTray = light.Value != 1;
}
}
var traySize = SystemInformation.SmallIconSize;
_notify = new NotifyIcon
{
Icon = new System.Drawing.Icon(darkTray ? Properties.Resources.Target : Properties.Resources.TargetDark, traySize.Width, traySize.Height),
Visible = true,
ContextMenu =
new ContextMenu(
new MenuItem[]
{
new MenuItem("Settings", Settings),
new MenuItem("-"),
new MenuItem("Exit", Exit),
}
),
Text = "ClickPaste: Click to choose a target"
};
_notify.MouseDown += _notify_MouseDown;
}
private void HotKeyManager_HotKeyPressed(object sender, HotKeyEventArgs e)
{
StopHotKey();
// wait until control keys are no longer pressed
while (Native.IsModifierKeyPressed())
{
Thread.Sleep(300);
}
switch((HotKeyMode) Properties.Settings.Default.HotKeyMode)
{
case HotKeyMode.Target:
StartTrack();
break;
case HotKeyMode.JustGo:
StartTyping();
break;
}
}
private void HotKeyManager_EscapePressed(object sender, HotKeyEventArgs e)
{
StopHotKey();
_stop.Cancel();
}
void StartTrack()
{
if (_hook == null)
{
uint[] Cursors = { Native.NORMAL, Native.IBEAM, Native.HAND };
for (int i = 0; i < Cursors.Length; i++)
Native.SetSystemCursor(Native.CopyIcon(Native.LoadCursor(IntPtr.Zero, (int)Native.CROSS)), Cursors[i]);
_hook = Hook.GlobalEvents();
_hook.MouseUp += _hook_MouseUp;
_hook.KeyDown += _hook_KeyDown;
}
}
private void _hook_KeyDown(object sender, KeyEventArgs e)
{
if(e.KeyCode == Keys.Escape)
{
EndTrack();
}
}
void EndTrack()
{
if (_hook != null)
{
_hook.MouseUp -= _hook_MouseUp;
_hook.KeyDown -= _hook_KeyDown;
_hook.Dispose();
_hook = null;
Native.SystemParametersInfo(0x0057, 0, null, 0);
}
}
private void _notify_MouseDown(object sender, MouseEventArgs e)
{
switch(e.Button)
{
//case MouseButtons.Middle:
case MouseButtons.Left: // this is a lie, we only get left after mouse released
if (!_settingsOpen)
{
StartTrack();
}
break;
}
}
private void _hook_MouseUp(object sender, MouseEventArgs e)
{
switch (e.Button)
{
case MouseButtons.Left:
//case MouseButtons.Middle:
EndTrack();
StartTyping();
break;
}
}
void StartTyping()
{
var clip = Clipboard.GetText();
// whatever window is under focus right now should be the target
if (Properties.Settings.Default.Confirm && clip.Length > Properties.Settings.Default.ConfirmOver)
{
SystemSounds.Beep.Play();
var w = Native.GetForegroundWindow();
if (DialogResult.Yes != MessageBox.Show($"Confirm typing {clip.Length} characters to window '{Native.GetText(w).First(50)}'?", "ClickPaste Confirm Typing", MessageBoxButtons.YesNo))
{
StartHotKey();// resume normal hotkey listening
Native.SetForegroundWindow(w);
return;
}
Native.SetForegroundWindow(w);
}
_stop = new CancellationTokenSource();
Task.Run(() =>
{
// check if it's my window
//IntPtr hwnd = Native.WindowFromPoint(e.X, e.Y);
// ... we don't have a window yet
if (string.IsNullOrEmpty(clip))
{
// nothing to paste
SystemSounds.Beep.Play();
}
else
{
var cancel = _stop.Token;
var traySize = SystemInformation.SmallIconSize;
var icon = _notify.Icon;
_notify.Icon = new System.Drawing.Icon(Properties.Resources.Typing, traySize.Width, traySize.Height);
int startDelayMS = Properties.Settings.Default.StartDelayMS;
Thread.Sleep(100 + startDelayMS);
StartHotKeyEscape();
int keyDelayMS = Properties.Settings.Default.KeyDelayMS;
var method = (TypeMethod)Properties.Settings.Default.TypeMethod;
IList<string> list = PrepareKeystrokes(clip, method);
if (TypeMethod.AutoIt_Send == method)
{
AutoIt.AutoItX.AutoItSetOption("SendKeyDelay", 0);
}
foreach (var s in list)
{
switch (method)
{
case TypeMethod.AutoIt_Send:
AutoIt.AutoItX.Send(s, 1);
break;
case TypeMethod.Forms_SendKeys:
SendKeys.SendWait(s);
break;
}
Thread.Sleep(keyDelayMS);
if (cancel.IsCancellationRequested)
{
break;//stop typing early
}
}
_notify.Icon = icon;
}
StartHotKey();// resume normal hotkey listening
});
}
IList<string> PrepareKeystrokes(string raw, TypeMethod method)
{
var list = new List<string>();
var specials = @"{}[]+^%~()";
foreach(char c in raw)
{
if(method == TypeMethod.Forms_SendKeys && (-1 != specials.IndexOf(c)))
{
list.Add("{" + c.ToString() + "}");
}
else
{
list.Add(c.ToString());
}
}
return list;
}
void StartHotKey()
{
StopHotKey();
var hotkeyLetter = Properties.Settings.Default.HotKey;
if (!string.IsNullOrEmpty(hotkeyLetter))
{
try
{
Keys HotKey = (Keys)Enum.Parse(typeof(Keys), hotkeyLetter);
_usingHotKey = HotKeyManager.RegisterHotKey(HotKey, (KeyModifiers)Properties.Settings.Default.HotKeyModifier);
_currentHotKeyHandler = new EventHandler<HotKeyEventArgs>(HotKeyManager_HotKeyPressed);
HotKeyManager.HotKeyPressed += _currentHotKeyHandler;
}
catch(Exception e)
{
MessageBox.Show("Could not register hot key: " + e.Message);
}
}
}
void StartHotKeyEscape()
{
StopHotKey();
try
{
_usingHotKey = HotKeyManager.RegisterHotKey(Keys.Escape, KeyModifiers.None);
_currentHotKeyHandler = new EventHandler<HotKeyEventArgs>(HotKeyManager_EscapePressed);
HotKeyManager.HotKeyPressed += _currentHotKeyHandler;
}
catch (Exception e)
{
MessageBox.Show("Could not register hot key: " + e.Message);
}
}
void StopHotKey()
{
if(_usingHotKey.HasValue)
{
HotKeyManager.HotKeyPressed -= _currentHotKeyHandler;
HotKeyManager.UnregisterHotKey(_usingHotKey.Value);
}
_usingHotKey = null;
_currentHotKeyHandler = null;
}
void Settings(object sender, EventArgs e)
{
if (_settingsOpen)
{
return;
}
_settingsOpen = true;
StopHotKey();
var settings = new SettingsForm();
settings.ShowDialog();
_settingsOpen = false;
StartHotKey();
}
void Exit(object sender, EventArgs e)
{
EndTrack();
// Hide tray icon, otherwise it will remain shown until user mouses over it
_notify.Visible = false;
_notify.Dispose();
StopHotKey();
Application.Exit();
}
}
}