Repository navigation
Expand file tree
/
Copy pathRSPaster.cs
More file actions
1287 lines (1161 loc) · 52.4 KB
/
Copy pathRSPaster.cs
File metadata and controls
1287 lines (1161 loc) · 52.4 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
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
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// RSPaster - types multi-line text into whatever window has focus, for targets
// that ignore the clipboard: hypervisor VM consoles, VNC, IPMI/BMC KVM, and UAC
// prompts shown on the normal desktop.
//
// C# 5 only (in-box csc).
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.Globalization;
using System.Security.Principal;
using System.Threading;
using System.Windows.Forms;
namespace RSPaster
{
public class MainForm : Form
{
const int HOTKEY_ID = 1;
const int HOTKEY_GRAB_ID = 2;
const int WM_HOTKEY = 0x0312;
const uint MOD_ALT = 0x0001;
const uint MOD_CONTROL = 0x0002;
const uint VK_V = 0x56;
const uint VK_G = 0x47;
const string HOTKEY_LABEL = "Ctrl+Alt+V";
const string GRAB_HOTKEY_LABEL = "Ctrl+Alt+G";
enum RunState { Idle, Countdown, Typing }
Settings _settings;
Panel _topBar;
Panel _content;
Panel _bottom;
Panel _statusBar;
ScrollAwareTextBox _txtInput;
InputHost _txtHost;
ThemedScrollBar _scroll;
bool _syncing;
SpinBox _startDelay;
SpinBox _keyDelay;
SpinBox _lineDelay;
Label _lblStart;
Label _lblKey;
Label _lblLineUnit;
ThemedCheck _chkLineDelay;
ThemedCheck _chkHideText;
ThemedCheck _chkUnicode;
ThemedCheck _chkEnterAtEnd;
ThemedCheck _chkClearAfter;
ThemedCheck _chkOnTop;
ThemedButton _btnGo;
ThemedButton _btnTheme;
ThemedButton _btnPhrases;
ThemedButton _btnGrab;
PhrasePanel _phrases;
Label _lblStatus;
Label _lnkAdmin;
ToolTip _tip;
ContextMenuStrip _themeMenu;
NotifyIcon _tray;
ContextMenuStrip _trayMenu;
ToolStripMenuItem _trayShow;
ToolStripMenuItem _trayType;
IntPtr _iconHandle = IntPtr.Zero;
System.Windows.Forms.Timer _countdownTimer;
RunState _state = RunState.Idle;
string _armedText;
string _armedLabel; // null = the main box; otherwise the phrase's label
string _targetName; // the process the keystrokes went to, for the status bar
int _remainingSeconds;
volatile bool _cancelRequested;
bool _hotkeyRegistered;
bool _grabHotkeyRegistered;
bool _grabbing;
bool _exiting;
bool _trayHintShown;
bool _showAdminLink;
string _baseTitle = "RSPaster";
public MainForm()
{
_settings = Settings.Load();
Th.Set(_settings.Theme);
if (IsElevated()) _baseTitle += " [Admin]";
Text = _baseTitle;
// Layout is scaled by hand through Dpi.S(), so WinForms must not
// scale it a second time. Left at its default the container would
// apply its own font-based factor on top, and at 150% the window
// comes out at 2.25x: controls off the edge, text clipped.
AutoScaleMode = AutoScaleMode.None;
// At a high scale on a small panel the scaled defaults can exceed
// the screen, and a MinimumSize taller than the work area leaves a
// window that cannot be resized back into view.
Rectangle work = Screen.PrimaryScreen.WorkingArea;
MinimumSize = new Size(
Math.Min(Dpi.S(520), work.Width),
Math.Min(Dpi.S(500), work.Height));
ClientSize = new Size(
Math.Min(_settings.WindowWidth >= Dpi.S(520) ? _settings.WindowWidth : Dpi.S(600),
work.Width - Dpi.S(40)),
Math.Min(_settings.WindowHeight >= Dpi.S(500) ? _settings.WindowHeight : Dpi.S(530),
work.Height - Dpi.S(60)));
StartPosition = FormStartPosition.CenterScreen;
KeyPreview = true;
TopMost = _settings.AlwaysOnTop;
Font = new Font("Segoe UI", 9F);
DoubleBuffered = true;
BuildTopBar();
BuildStatusBar();
BuildContent();
BuildThemeMenu();
BuildTray();
// Docked children are z-ordered back to front, so Fill is added first.
Controls.Add(_content);
Controls.Add(_topBar);
Controls.Add(_statusBar);
_countdownTimer = new System.Windows.Forms.Timer();
_countdownTimer.Interval = 1000;
_countdownTimer.Tick += delegate(object s, EventArgs e) { OnCountdownTick(); };
Th.Changed += delegate(object s, EventArgs e) { ApplyTheme(); };
ApplyTheme();
}
// ---- construction ---------------------------------------------------
void BuildTopBar()
{
_topBar = new Panel();
_topBar.Dock = DockStyle.Top;
_topBar.Height = Dpi.S(42);
_topBar.Paint += PaintTopBar;
_btnTheme = new ThemedButton();
_btnTheme.Text = "Theme";
_btnTheme.Size = new Size(Dpi.S(84), Dpi.S(26));
_btnTheme.Anchor = AnchorStyles.Top | AnchorStyles.Right;
_btnTheme.Click += delegate(object s, EventArgs e)
{
MenuTheme.Apply(_themeMenu);
_themeMenu.Show(_btnTheme, new Point(0, _btnTheme.Height + 2));
};
_btnPhrases = new ThemedButton();
_btnPhrases.Text = "Phrases";
_btnPhrases.Size = new Size(Dpi.S(84), Dpi.S(26));
_btnPhrases.Anchor = AnchorStyles.Top | AnchorStyles.Right;
_btnPhrases.Click += delegate(object s, EventArgs e)
{
_phrases.Visible = !_phrases.Visible;
};
_btnGrab = new ThemedButton();
_btnGrab.Text = "OCR";
_btnGrab.Size = new Size(Dpi.S(66), Dpi.S(26));
_btnGrab.Anchor = AnchorStyles.Top | AnchorStyles.Right;
_btnGrab.Click += delegate(object s, EventArgs e) { StartGrab(); };
_topBar.Controls.Add(_btnTheme);
_topBar.Controls.Add(_btnPhrases);
_topBar.Controls.Add(_btnGrab);
_topBar.Resize += delegate(object s, EventArgs e) { LayoutTopBar(); };
LayoutTopBar();
}
void LayoutTopBar()
{
_btnTheme.Location = new Point(_topBar.Width - _btnTheme.Width - Dpi.S(12), Dpi.S(8));
_btnPhrases.Location = new Point(_btnTheme.Left - _btnPhrases.Width - Dpi.S(8), Dpi.S(8));
_btnGrab.Location = new Point(_btnPhrases.Left - _btnGrab.Width - Dpi.S(8), Dpi.S(8));
}
void PaintTopBar(object sender, PaintEventArgs e)
{
Theme t = Th.T;
e.Graphics.Clear(t.Panel);
using (Pen p = new Pen(t.Border))
e.Graphics.DrawLine(p, 0, _topBar.Height - 1, _topBar.Width, _topBar.Height - 1);
Brand.PaintMark(e.Graphics, new Rectangle(Dpi.S(11), Dpi.S(10), Dpi.S(22), Dpi.S(22)), t.Accent, t.Accent);
using (Font f = new Font("Segoe UI", 10.5F, FontStyle.Bold))
TextRenderer.DrawText(e.Graphics, "RSPaster", f,
new Rectangle(Dpi.S(40), 0, Dpi.S(220), _topBar.Height - 1), t.Txt,
TextFormatFlags.Left | TextFormatFlags.VerticalCenter);
using (Font f = new Font("Segoe UI", 8.25F))
TextRenderer.DrawText(e.Graphics, _hotkeyRegistered ? HOTKEY_LABEL : "hotkey unavailable", f,
new Rectangle(Dpi.S(122), 0, Dpi.S(200), _topBar.Height - 1), t.TxtDim,
TextFormatFlags.Left | TextFormatFlags.VerticalCenter);
}
void BuildStatusBar()
{
_statusBar = new Panel();
_statusBar.Dock = DockStyle.Bottom;
_statusBar.Height = Dpi.S(26);
_statusBar.Paint += delegate(object s, PaintEventArgs e)
{
e.Graphics.Clear(Th.T.Panel);
using (Pen p = new Pen(Th.T.Border))
e.Graphics.DrawLine(p, 0, 0, _statusBar.Width, 0);
};
_lblStatus = new Label();
_lblStatus.AutoSize = false;
_lblStatus.Location = new Point(Dpi.S(11), 1);
_lblStatus.Size = new Size(Dpi.S(380), Dpi.S(24));
_lblStatus.TextAlign = ContentAlignment.MiddleLeft;
_lblStatus.Anchor = AnchorStyles.Left | AnchorStyles.Top | AnchorStyles.Right;
_lblStatus.Text = "Paste text, then focus the target during the countdown.";
_lnkAdmin = new Label();
_lnkAdmin.AutoSize = true;
_lnkAdmin.TextAlign = ContentAlignment.MiddleRight;
_lnkAdmin.Text = "Restart as Admin";
_lnkAdmin.Cursor = Cursors.Hand;
_lnkAdmin.Anchor = AnchorStyles.Right | AnchorStyles.Top;
// Kept in a field, not read back from _lnkAdmin.Visible: that
// getter reports effective visibility, so while the form is still
// being built and the parent is not shown it answers false, and
// the layout below would hand the link's space to the status text
// and then overlap them.
// Hidden on the source path, and not only because the UAC prompt
// would say "Windows PowerShell" instead of RSPaster. Elevating
// that path runs Run-From-Source.ps1 with the execution policy
// bypassed, and that script compiles and executes every .cs file
// sitting beside it, unsigned and unchecked. Anything that can
// write to that folder - which includes anything already running
// as this user, from a folder DEPLOY.md recommends - would get
// high integrity the moment an administrator clicked the link.
// Building the exe first is a reasonable price for elevating.
_showAdminLink = !IsElevated() && !Program.RunningFromSource;
_lnkAdmin.Visible = _showAdminLink;
_lnkAdmin.Click += delegate(object s, EventArgs e) { RestartAsAdmin(); };
_statusBar.Controls.Add(_lblStatus);
_statusBar.Controls.Add(_lnkAdmin);
_statusBar.Resize += delegate(object s, EventArgs e) { LayoutStatusBar(); };
}
void LayoutStatusBar()
{
if (_showAdminLink)
{
_lnkAdmin.Location = new Point(_statusBar.Width - _lnkAdmin.Width - Dpi.S(11), Dpi.S(5));
_lblStatus.Size = new Size(Math.Max(Dpi.S(80), _lnkAdmin.Left - Dpi.S(20)), Dpi.S(24));
}
else
{
// Running elevated hides the link; give the space to status
// text, which is where line-wait countdowns live.
_lblStatus.Size = new Size(_statusBar.Width - Dpi.S(22), Dpi.S(24));
}
}
void BuildContent()
{
_content = new Panel();
_content.Dock = DockStyle.Fill;
_content.Padding = new Padding(Dpi.S(12), Dpi.S(12), Dpi.S(12), Dpi.S(8));
_txtInput = new ScrollAwareTextBox();
_txtInput.Multiline = true;
_txtInput.AcceptsReturn = true;
_txtInput.AcceptsTab = true;
// Wrapping on is what removes the need for a horizontal scrollbar,
// and for reviewing a long command before sending it, seeing the
// whole line beats scrolling sideways through it.
_txtInput.WordWrap = true;
_txtInput.ScrollBars = ScrollBars.None;
_txtInput.BorderStyle = BorderStyle.None;
_txtInput.Font = new Font("Consolas", 10F);
_txtHost = new InputHost(_txtInput, Dpi.S(6), Dpi.S(5));
_txtHost.Dock = DockStyle.Fill;
_scroll = new ThemedScrollBar();
_scroll.Dock = DockStyle.Right;
_txtHost.Controls.Add(_scroll); // docks before the Fill child
_txtInput.ViewChanged += delegate(object s, EventArgs e) { SyncScrollFromText(); };
_txtInput.TextChanged += delegate(object s, EventArgs e) { SyncScrollFromText(); };
_scroll.UserScrolled += delegate(object s, EventArgs e)
{
if (_syncing) return;
_syncing = true;
_txtInput.ScrollToLine(_scroll.Value);
_syncing = false;
};
_bottom = new Panel();
_bottom.Dock = DockStyle.Bottom;
_bottom.Height = Dpi.S(152);
_lblStart = MakeLabel("Start delay (s)");
_startDelay = new SpinBox(0, 60, _settings.StartDelaySeconds);
_lblKey = MakeLabel("Key delay (ms)");
_keyDelay = new SpinBox(0, 500, _settings.KeyDelayMs);
// Held in a field, not a local. A ToolTip is a Component, not a
// child control, so nothing else keeps it alive: as a local it
// becomes garbage the moment this method returns, and whenever the
// finalizer happens to run it destroys the native tooltip window
// underneath a tip that may be on screen. That is the random part
// of tooltips flickering and leaving fragments behind.
_tip = new ToolTip();
// Owner-drawn, because the stock tooltip is a system light box:
// jarring on 20-odd dark palettes, and its pale rectangle covers
// neighboring controls, so any imperfect repaint on dismissal
// shows up as stray light edges.
_tip.OwnerDraw = true;
_tip.Draw += OnDrawToolTip;
_chkUnicode = MakeCheck("Unicode mode", _settings.UnicodeMode);
_tip.SetToolTip(_chkUnicode,
"Send every character as a unicode event instead of scancodes.\r\n" +
"Use this if the typed output comes out garbled, which means the\r\n" +
"target's keyboard layout differs from yours.");
_chkLineDelay = MakeCheck("Delay between lines", _settings.LineDelayEnabled);
_lineDelay = new SpinBox(0, 600, _settings.LineDelaySeconds);
_lineDelay.Enabled = _settings.LineDelayEnabled;
_lblLineUnit = MakeLabel("seconds");
_chkLineDelay.CheckedChanged += delegate(object s, EventArgs e)
{
_lineDelay.Enabled = _chkLineDelay.Checked;
};
string lineDelayHelp =
"Wait after each Enter before typing the next line.\r\n" +
"For slow or busy machines where a command needs time to\r\n" +
"finish before the next one can be entered. Cancel stays\r\n" +
"responsive during the wait.";
_tip.SetToolTip(_chkLineDelay, lineDelayHelp);
_tip.SetToolTip(_lineDelay, lineDelayHelp);
_chkHideText = MakeCheck("Hide text", _settings.HideText);
_tip.SetToolTip(_chkHideText,
"Show the text as dots, for a password on a shared screen.\r\n" +
"Pasting still works and replaces the whole box; untick to\r\n" +
"edit by hand. What gets typed is unchanged either way.");
_chkHideText.CheckedChanged += delegate(object s, EventArgs e)
{
_txtInput.Masked = _chkHideText.Checked;
_txtInput.ReadOnly = _chkHideText.Checked;
SetStatus(_chkHideText.Checked
? "Text hidden. Paste replaces it; untick Hide text to edit."
: "Text visible again.");
SyncScrollFromText();
};
// MakeCheck sets Checked before the handler above exists, so a
// remembered hideText=true would leave the box unmasked while the
// checkbox claimed otherwise, and the next paste would appear in
// clear. Apply the restored state directly.
_txtInput.Masked = _chkHideText.Checked;
_txtInput.ReadOnly = _chkHideText.Checked;
_chkEnterAtEnd = MakeCheck("Press Enter at end", _settings.EnterAtEnd);
_chkClearAfter = MakeCheck("Clear after typing", _settings.ClearAfter);
_chkOnTop = MakeCheck("Always on top", _settings.AlwaysOnTop);
_chkOnTop.CheckedChanged += delegate(object s, EventArgs e)
{
TopMost = _chkOnTop.Checked;
};
_btnGo = new ThemedButton();
_btnGo.Primary = true;
_btnGo.Font = new Font("Segoe UI", 9.75F, FontStyle.Bold);
_btnGo.SetBounds(0, Dpi.S(110), Dpi.S(100), Dpi.S(36));
_btnGo.Anchor = AnchorStyles.Left | AnchorStyles.Right | AnchorStyles.Top;
_btnGo.Click += delegate(object s, EventArgs e) { StartOrCancel(); };
LayoutBottom();
_bottom.Controls.Add(_lblStart);
_bottom.Controls.Add(_startDelay);
_bottom.Controls.Add(_lblKey);
_bottom.Controls.Add(_keyDelay);
_bottom.Controls.Add(_chkUnicode);
_bottom.Controls.Add(_chkLineDelay);
_bottom.Controls.Add(_lineDelay);
_bottom.Controls.Add(_lblLineUnit);
_bottom.Controls.Add(_chkHideText);
_bottom.Controls.Add(_chkEnterAtEnd);
_bottom.Controls.Add(_chkClearAfter);
_bottom.Controls.Add(_chkOnTop);
_bottom.Controls.Add(_btnGo);
_bottom.Resize += delegate(object s, EventArgs e)
{
_btnGo.Width = Math.Max(Dpi.S(120), _bottom.Width);
};
_content.Controls.Add(_txtHost);
_content.Controls.Add(_bottom);
// Added after the Fill child so it docks above it. Contents are
// never persisted; Build receives only the remembered labels.
_phrases = new PhrasePanel();
List<string> labels = _settings.PhraseLabels;
if (labels.Count == 0)
{
labels = new List<string>();
labels.Add("Phrase 1");
labels.Add("Phrase 2");
labels.Add("Phrase 3");
}
_phrases.Build(labels);
_phrases.Visible = _settings.PhrasesVisible;
_phrases.TypeRequested += delegate(object s, PhraseTypeEventArgs e)
{
if (_state == RunState.Idle) StartCountdownWith(e.Text, e.Label);
else CancelRun();
};
_content.Controls.Add(_phrases);
}
void OnDrawToolTip(object sender, DrawToolTipEventArgs e)
{
Theme t = Th.T;
using (SolidBrush b = new SolidBrush(t.Panel))
e.Graphics.FillRectangle(b, e.Bounds);
using (Pen p = new Pen(t.Border))
e.Graphics.DrawRectangle(p, new Rectangle(
e.Bounds.X, e.Bounds.Y, e.Bounds.Width - 1, e.Bounds.Height - 1));
Rectangle text = Rectangle.Inflate(e.Bounds, -Dpi.S(4), -Dpi.S(2));
TextRenderer.DrawText(e.Graphics, e.ToolTipText, e.Font, text, t.Txt,
TextFormatFlags.Left | TextFormatFlags.VerticalCenter);
}
void SyncScrollFromText()
{
if (_syncing) return;
_syncing = true;
_scroll.Configure(_txtInput.VisualLineCount, _txtInput.VisibleLines, _txtInput.FirstVisibleLine);
_syncing = false;
}
// Sized here rather than left to AutoSize, which is the same reason
// ThemedCheck has SizeToText. An AutoSize label reports the stock
// 100x23 default until it is parented, and LayoutBottom runs before
// that. Laying out against 100 happens to leave a gap at 100% and
// overlaps the next control at 150%, because 100 is a fixed pixel
// value that does not scale while the text does.
Label MakeLabel(string text)
{
Label l = new Label();
l.AutoSize = false;
l.Font = Font; // before measuring: unparented, it has no inherited font yet
l.Text = text;
l.TextAlign = ContentAlignment.MiddleLeft;
Size s = TextRenderer.MeasureText(text, l.Font, new Size(int.MaxValue, int.MaxValue),
TextFormatFlags.Left | TextFormatFlags.VerticalCenter | TextFormatFlags.NoPadding);
l.Size = new Size(s.Width + Dpi.S(2), s.Height + Dpi.S(2));
return l;
}
ThemedCheck MakeCheck(string text, bool chk)
{
ThemedCheck c = new ThemedCheck();
c.Font = Font;
c.Text = text;
c.Checked = chk;
c.SizeToText();
return c;
}
// Every control is placed after the one before it, so a wider font, a
// different DPI, or a reworded label pushes its neighbors along instead
// of colliding with them.
void LayoutBottom()
{
int gapS = Dpi.S(8); // label to its own field
int gapL = Dpi.S(18); // between groups
int spinW = Dpi.S(64);
int spinH = Dpi.S(27);
int row1 = Dpi.S(10);
int row2 = Dpi.S(45);
int row3 = Dpi.S(82);
_startDelay.Size = new Size(spinW, spinH);
_keyDelay.Size = new Size(spinW, spinH);
_lineDelay.Size = new Size(spinW, spinH);
_lblStart.Location = new Point(0, Middle(row1, spinH, _lblStart.Height));
_startDelay.Location = new Point(_lblStart.Right + gapS, row1);
_lblKey.Location = new Point(_startDelay.Right + gapL, Middle(row1, spinH, _lblKey.Height));
_keyDelay.Location = new Point(_lblKey.Right + gapS, row1);
_chkUnicode.Location = new Point(_keyDelay.Right + gapL, Middle(row1, spinH, _chkUnicode.Height));
_chkLineDelay.Location = new Point(0, Middle(row2, spinH, _chkLineDelay.Height));
_lineDelay.Location = new Point(_chkLineDelay.Right + gapS, row2);
_lblLineUnit.Location = new Point(_lineDelay.Right + gapS, Middle(row2, spinH, _lblLineUnit.Height));
_chkHideText.Location = new Point(_lblLineUnit.Right + gapL, Middle(row2, spinH, _chkHideText.Height));
_chkEnterAtEnd.Location = new Point(0, row3);
_chkClearAfter.Location = new Point(_chkEnterAtEnd.Right + gapL, row3);
_chkOnTop.Location = new Point(_chkClearAfter.Right + gapL, row3);
}
static int Middle(int rowTop, int rowHeight, int controlHeight)
{
return rowTop + (rowHeight - controlHeight) / 2;
}
void BuildThemeMenu()
{
_themeMenu = new ContextMenuStrip();
_themeMenu.Renderer = new ToolStripProfessionalRenderer(new ThemeColorTable());
_themeMenu.ShowImageMargin = false;
ToolStripMenuItem group = null;
foreach (Theme t in Themes.All)
{
ToolStripMenuItem item = new ToolStripMenuItem(t.Label);
item.Tag = t.Key;
item.Click += OnThemePicked;
if (t.Group == null)
{
_themeMenu.Items.Add(item);
}
else
{
if (group == null || group.Text != t.Group)
{
group = new ToolStripMenuItem(t.Group);
_themeMenu.Items.Add(group);
}
group.DropDownItems.Add(item);
}
}
_themeMenu.Opening += delegate(object s, CancelEventArgs e) { MarkActiveTheme(); };
}
void MarkActiveTheme()
{
foreach (ToolStripItem raw in _themeMenu.Items)
{
ToolStripMenuItem item = raw as ToolStripMenuItem;
if (item == null) continue;
if (item.HasDropDownItems)
{
foreach (ToolStripItem sub in item.DropDownItems)
{
ToolStripMenuItem s = sub as ToolStripMenuItem;
if (s != null) s.Checked = Equals(s.Tag, Th.T.Key);
}
}
else
{
item.Checked = Equals(item.Tag, Th.T.Key);
}
}
}
void OnThemePicked(object sender, EventArgs e)
{
ToolStripMenuItem item = (ToolStripMenuItem)sender;
Th.Set((string)item.Tag);
// SaveSettings, not _settings.Save(): the settings object still
// holds startup values, and writing it directly would revert any
// delay or checkbox the user changed since launch.
SaveSettings();
}
void BuildTray()
{
_trayMenu = new ContextMenuStrip();
_trayMenu.Renderer = new ToolStripProfessionalRenderer(new ThemeColorTable());
_trayMenu.ShowImageMargin = false;
_trayShow = new ToolStripMenuItem("Show RSPaster");
_trayShow.ToolTipText = "Restore the window";
_trayShow.Click += delegate(object s, EventArgs e) { RestoreWindow(); };
_trayType = new ToolStripMenuItem("Type after delay");
_trayType.ToolTipText = "Same as " + HOTKEY_LABEL + ": focus your target first";
_trayType.Click += delegate(object s, EventArgs e) { StartOrCancel(); };
ToolStripMenuItem exit = new ToolStripMenuItem("Exit");
exit.ToolTipText = "Quit RSPaster and release the hotkey";
exit.Click += delegate(object s, EventArgs e) { _exiting = true; Close(); };
_trayMenu.Items.Add(_trayShow);
_trayMenu.Items.Add(_trayType);
_trayMenu.Items.Add(new ToolStripSeparator());
_trayMenu.Items.Add(exit);
_trayMenu.Opening += delegate(object s, CancelEventArgs e)
{
_trayShow.Text = Visible ? "Hide RSPaster" : "Show RSPaster";
MenuTheme.Apply(_trayMenu);
};
_tray = new NotifyIcon();
_tray.ContextMenuStrip = _trayMenu;
_tray.Text = "RSPaster";
_tray.Visible = true;
_tray.DoubleClick += delegate(object s, EventArgs e)
{
if (Visible && WindowState != FormWindowState.Minimized) HideToTray(false);
else RestoreWindow();
};
}
// ---- theming --------------------------------------------------------
void ApplyTheme()
{
Theme t = Th.T;
BackColor = t.Panel2;
ForeColor = t.Txt;
_content.BackColor = t.Panel2;
_bottom.BackColor = t.Panel2;
_topBar.BackColor = t.Panel;
_statusBar.BackColor = t.Panel;
_txtInput.BackColor = t.Input;
_txtInput.ForeColor = t.Txt;
// .form-grid label { color: var(--se-txt-dim) }
_lblStart.BackColor = t.Panel2;
_lblStart.ForeColor = t.TxtDim;
_lblKey.BackColor = t.Panel2;
_lblKey.ForeColor = t.TxtDim;
_lblLineUnit.BackColor = t.Panel2;
_lblLineUnit.ForeColor = t.TxtDim;
_lblStatus.BackColor = t.Panel;
_lblStatus.ForeColor = t.TxtDim;
_lnkAdmin.BackColor = t.Panel;
_lnkAdmin.ForeColor = t.Accent;
UpdateTrayIcon();
OsChrome.ApplyTitleBar(this);
OsChrome.ApplyScrollBars(_txtInput);
_topBar.Invalidate();
_statusBar.Invalidate();
Invalidate(true);
}
void UpdateTrayIcon()
{
IntPtr old = _iconHandle;
Icon fresh = Brand.CreateIcon(32, out _iconHandle);
_tray.Icon = fresh;
Icon = fresh;
// Only safe once both the tray and the form have taken the new one.
if (old != IntPtr.Zero) Native.DestroyIcon(old);
}
// ---- window / tray behavior ---------------------------------------
protected override void OnShown(EventArgs e)
{
base.OnShown(e);
LayoutStatusBar(); // _lnkAdmin.Width is only final once shown
}
protected override void OnHandleCreated(EventArgs e)
{
base.OnHandleCreated(e);
_hotkeyRegistered = Native.RegisterHotKey(Handle, HOTKEY_ID, MOD_CONTROL | MOD_ALT, VK_V);
if (Ocr.IsAvailable)
{
_grabHotkeyRegistered = Native.RegisterHotKey(Handle, HOTKEY_GRAB_ID, MOD_CONTROL | MOD_ALT, VK_G);
_tip.SetToolTip(_btnGrab,
"Read text off the screen (" + GRAB_HOTKEY_LABEL + "):\r\n" +
"drag a rectangle over a console and the recognized text\r\n" +
"lands on the clipboard. Runs entirely on this machine.");
}
else
{
// Some LTSC and Server images ship no OCR language pack. The
// button stays visible so the capability is discoverable, but
// says why it is off.
_btnGrab.Enabled = false;
_tip.SetToolTip(_btnGrab, "This Windows has no OCR language pack, so OCR is unavailable.");
}
if (!_hotkeyRegistered)
SetStatus(HOTKEY_LABEL + " is taken by another app - use the button instead.");
UpdateGoButtonText();
// The constructor ran before there was a handle to theme.
OsChrome.ApplyTitleBar(this);
OsChrome.ApplyScrollBars(_txtInput);
_topBar.Invalidate();
}
protected override void OnHandleDestroyed(EventArgs e)
{
if (_hotkeyRegistered) Native.UnregisterHotKey(Handle, HOTKEY_ID);
if (_grabHotkeyRegistered) Native.UnregisterHotKey(Handle, HOTKEY_GRAB_ID);
base.OnHandleDestroyed(e);
}
protected override void WndProc(ref Message m)
{
if (m.Msg == WM_HOTKEY && m.WParam.ToInt32() == HOTKEY_ID)
{
// No Activate() here on purpose: when the hotkey fires, the
// target window must keep focus or the keys land in RSPaster.
StartOrCancel();
return;
}
if (m.Msg == WM_HOTKEY && m.WParam.ToInt32() == HOTKEY_GRAB_ID)
{
StartGrab();
return;
}
base.WndProc(ref m);
}
protected override void OnResize(EventArgs e)
{
base.OnResize(e);
if (WindowState == FormWindowState.Minimized) HideToTray(true);
}
protected override void OnFormClosing(FormClosingEventArgs e)
{
SaveSettings();
// X hides rather than exits, so the hotkey survives; Exit lives in
// the tray menu. Windows shutdown and task-manager close still win.
if (!_exiting && e.CloseReason == CloseReason.UserClosing)
{
e.Cancel = true;
HideToTray(true);
return;
}
_tray.Visible = false;
base.OnFormClosing(e);
}
protected override void OnFormClosed(FormClosedEventArgs e)
{
_cancelRequested = true;
if (_tip != null) _tip.Dispose();
_tray.Visible = false;
_tray.Dispose();
if (_iconHandle != IntPtr.Zero) Native.DestroyIcon(_iconHandle);
base.OnFormClosed(e);
}
void HideToTray(bool announce)
{
// Hide() alone removes the taskbar button; toggling ShowInTaskbar
// would recreate the window handle each way, unregistering and
// re-registering the hotkey and reapplying the OS chrome for nothing.
Hide();
if (announce && !_trayHintShown)
{
_trayHintShown = true;
_tray.BalloonTipTitle = "RSPaster is still running";
_tray.BalloonTipText = _hotkeyRegistered
? HOTKEY_LABEL + " still works. Right-click the tray icon to exit."
: "Right-click the tray icon to show the window or exit.";
_tray.ShowBalloonTip(4000);
}
}
void RestoreWindow()
{
Show();
WindowState = FormWindowState.Normal;
Activate();
_txtInput.Focus();
}
void SaveSettings()
{
_settings.StartDelaySeconds = _startDelay.Value;
_settings.KeyDelayMs = _keyDelay.Value;
_settings.LineDelayEnabled = _chkLineDelay.Checked;
_settings.LineDelaySeconds = _lineDelay.Value;
_settings.EnterAtEnd = _chkEnterAtEnd.Checked;
_settings.ClearAfter = _chkClearAfter.Checked;
_settings.AlwaysOnTop = _chkOnTop.Checked;
_settings.UnicodeMode = _chkUnicode.Checked;
_settings.HideText = _chkHideText.Checked;
_settings.PhrasesVisible = _phrases.Visible;
_settings.PhraseLabels = _phrases.Labels;
_settings.Theme = Th.T.Key;
if (WindowState == FormWindowState.Normal)
{
_settings.WindowWidth = ClientSize.Width;
_settings.WindowHeight = ClientSize.Height;
}
_settings.Save();
}
// ---- typing ---------------------------------------------------------
protected override void OnKeyDown(KeyEventArgs e)
{
if (e.KeyCode == Keys.Escape && _state != RunState.Idle)
{
StartOrCancel();
e.Handled = true;
return;
}
base.OnKeyDown(e);
}
void StartOrCancel()
{
if (_state == RunState.Idle) StartCountdown();
else CancelRun();
}
void StartCountdown()
{
StartCountdownWith(_txtInput.RealText, null);
}
void StartCountdownWith(string text, string label)
{
if (text.Length == 0)
{
SetStatus(label == null
? "Nothing to type - paste some text first."
: "'" + label + "' is empty - paste something into it first.");
return;
}
_armedText = text;
_armedLabel = label;
_state = RunState.Countdown;
_cancelRequested = false;
SetInputsEnabled(false);
UpdateGoButtonText();
// Park focus on the main button, which stays enabled as Cancel.
// Two subtleties, both learned by measuring where focus actually
// ended up: disabling the just-clicked phrase Type button ejects
// focus to the next control in tab order (which looked like Tab
// jumping into the next phrase box), and the Button's own click
// processing re-asserts focus on itself AFTER the Click handler
// returns, overriding any parking done inside it. BeginInvoke runs
// once the click message is fully processed, so it wins both races.
if (Visible)
{
BeginInvoke(new Action(delegate()
{
if (_state != RunState.Idle && _btnGo.CanFocus) _btnGo.Focus();
}));
}
_remainingSeconds = _startDelay.Value;
if (_remainingSeconds <= 0)
{
BeginTyping();
}
else
{
UpdateCountdownUi();
_countdownTimer.Start();
}
}
void OnCountdownTick()
{
_remainingSeconds--;
if (_remainingSeconds > 0)
{
UpdateCountdownUi();
}
else
{
_countdownTimer.Stop();
BeginTyping();
}
}
void UpdateCountdownUi()
{
SetStatus(string.Format(CultureInfo.InvariantCulture,
_armedLabel == null
? "Typing in {0}s - focus the target window now."
: "Typing '{1}' in {0}s - focus the target window now.",
_remainingSeconds, _armedLabel));
Text = string.Format(CultureInfo.InvariantCulture, "[{0}] {1}", _remainingSeconds, _baseTitle);
}
// Everything that has to be true about the target before a single
// keystroke goes out. Returns false having already reported why.
//
// This is a pre-flight check rather than an after-the-fact one because
// SendInput cannot report the failure that matters: when UIPI discards
// injected input - an unelevated process typing into an elevated
// window - the call still returns the full count and GetLastError
// still says success. The old "N keystrokes were blocked" message
// therefore could never fire for elevation, which is the one thing it
// named. The blocked counter is kept, because it still catches real
// SendInput failures, but it no longer claims to detect elevation.
bool TargetIsSafe()
{
if (!Target.InputDesktopReachable())
{
AbortRun("The desktop is locked or a UAC prompt is up - keystrokes would go nowhere.");
return false;
}
Target.Info t = Target.Foreground();
if (t.IsSelf)
{
// Typing into ourselves does nothing useful and is actively
// harmful: focus is parked on the button that is Cancel during
// a run, so a space or newline in the text presses it.
AbortRun("RSPaster is the focused window - focus the target first.");
return false;
}
int own = Target.Own();
if (t.Integrity > 0 && own > 0 && t.Integrity > own)
{
string what = t.ProcessName == null ? "That window" : "'" + t.ProcessName + "'";
AbortRun(what + " runs elevated - every keystroke would be discarded. "
+ (_showAdminLink ? "Use Restart as Admin."
: "Run RSPaster as administrator."));
return false;
}
_targetName = t.ProcessName;
return true;
}
// Puts the UI back the way FinishTyping would, for a run that never
// started. Without this the form stays locked with the button reading
// Cancel and no run behind it.
void AbortRun(string why)
{
_state = RunState.Idle;
Text = _baseTitle;
UpdateGoButtonText();
SetInputsEnabled(true);
SetStatus(why);
_armedText = null;
_armedLabel = null;
}
void BeginTyping()
{
_state = RunState.Typing;
Text = "[typing] " + _baseTitle;
if (!TargetIsSafe()) return;
// Naming the target turns the countdown from a blind safeguard
// into a visible one: a mistimed Alt+Tab or a chat window stealing
// focus is otherwise invisible until the password is already gone.
SetStatus(_targetName == null ? "Typing..." : "Typing into: " + _targetName);
string text = _armedText;
bool phraseRun = _armedLabel != null;
TypeOptions options = new TypeOptions();
options.AppendEnter = _chkEnterAtEnd.Checked;
options.PerKeyDelayMs = _keyDelay.Value;
options.UnicodeMode = _chkUnicode.Checked;
options.LineDelayMs = _chkLineDelay.Checked ? _lineDelay.Value * 1000 : 0;
options.Cancelled = delegate() { return _cancelRequested; };
string into = _targetName == null ? "" : " into " + _targetName;
options.Progress = delegate(int done, int total)
{
// A phrase is a secret: progress must not reveal its length.
Report(phraseRun ? "Typing" + into + "..." : string.Format(
CultureInfo.InvariantCulture,
"Typing{0}... {1}/{2} characters", into, done, total));
};
options.LineWait = delegate(int msLeft, int nextLine, int totalLines)
{
Report(string.Format(CultureInfo.InvariantCulture,
"Waiting {0}s before line {1} of {2}. Esc cancels.",
(msLeft + 999) / 1000, nextLine, totalLines));
};
Thread worker = new Thread(delegate()
{
TypeResult result = KeySender.TypeText(text, options);
OnUiThread(new Action(delegate() { FinishTyping(result); }));
});
worker.IsBackground = true;
worker.Start();
}
void FinishTyping(TypeResult result)
{
_state = RunState.Idle;
Text = _baseTitle;
UpdateGoButtonText();
SetInputsEnabled(true);