-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGrabOverlay.cs
More file actions
359 lines (324 loc) · 13.5 KB
/
Copy pathGrabOverlay.cs
File metadata and controls
359 lines (324 loc) · 13.5 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
// The region selector for Grab: a borderless window covering every monitor,
// showing a frozen screenshot dimmed, with the dragged rectangle shown at full
// brightness. Mouse up returns the cropped region; Escape returns nothing.
//
// The screen is frozen FIRST and the overlay shows the freeze, rather than
// dimming the live desktop, so the region being read cannot change between
// aiming and capturing - on a console that is actively printing, that gap is
// exactly when a line would scroll away.
//
// C# 5 only (in-box csc).
using System;
using System.Drawing;
using System.IO;
using System.Threading;
using System.Windows.Forms;
namespace RSPaster
{
// The one place text leaves RSPaster.
//
// "Nothing leaves the machine" is true of the OCR engine, and it stopped
// being true one line later: a plain Clipboard.SetText is captured by
// Clipboard History on a default Windows 10/11 install, and uploaded to the
// Microsoft account's cloud clipboard if "Sync across your devices" is on.
// What OCR reads is whatever was on the console - a root prompt, a printed
// key, an address plan - so the opt-outs below are not decoration. They are
// the same formats password managers use.
public static class Clip
{
// Returns false if the clipboard could not be written.
public static bool Put(string text)
{
if (text == null || text.Length == 0) text = " ";
// Another app holding the clipboard open is normal and brief:
// clipboard managers and Office grab it for a few milliseconds
// after every write. Retry before calling it locked.
for (int attempt = 0; ; attempt++)
{
try
{
DataObject data = new DataObject();
data.SetText(text);
// Presence with a zero DWORD is what the shell reads. Each
// format needs its own stream: they are read in turn, and a
// shared one would already be at its end after the first.
data.SetData("ExcludeClipboardContentFromMonitorProcessing", Zero());
data.SetData("CanIncludeInClipboardHistory", Zero());
data.SetData("CanUploadToCloudClipboard", Zero());
Clipboard.SetDataObject(data, true);
return true;
}
catch (System.Runtime.InteropServices.ExternalException)
{
if (attempt >= 3) return false;
Thread.Sleep(10);
}
}
}
static MemoryStream Zero()
{
return new MemoryStream(new byte[] { 0, 0, 0, 0 });
}
}
public class GrabOverlay : Form
{
readonly Bitmap _frozen;
readonly Rectangle _screenBounds;
Point _anchor;
Rectangle _selection;
bool _dragging;
// The selected crop, in a bitmap of its own. Null when cancelled.
public Bitmap Result;
public static Bitmap CaptureVirtualScreen(out Rectangle bounds)
{
bounds = SystemInformation.VirtualScreen;
Bitmap shot = new Bitmap(bounds.Width, bounds.Height);
using (Graphics g = Graphics.FromImage(shot))
g.CopyFromScreen(bounds.Left, bounds.Top, 0, 0, bounds.Size);
return shot;
}
// The screenshot is injected rather than taken here so tests can hand
// in a synthetic frame and exercise selection without touching the
// real desktop.
public GrabOverlay(Bitmap frozen, Rectangle screenBounds)
{
_frozen = frozen;
_screenBounds = screenBounds;
FormBorderStyle = FormBorderStyle.None;
StartPosition = FormStartPosition.Manual;
Bounds = screenBounds;
TopMost = true;
ShowInTaskbar = false;
Cursor = Cursors.Cross;
KeyPreview = true;
DoubleBuffered = true;
}
protected override void OnKeyDown(KeyEventArgs e)
{
if (e.KeyCode == Keys.Escape)
{
Result = null;
DialogResult = DialogResult.Cancel;
Close();
return;
}
base.OnKeyDown(e);
}
protected override void OnMouseDown(MouseEventArgs e)
{
_dragging = true;
_anchor = e.Location;
_selection = new Rectangle(e.Location, Size.Empty);
Invalidate();
base.OnMouseDown(e);
}
protected override void OnMouseMove(MouseEventArgs e)
{
if (_dragging)
{
_selection = Rectangle.FromLTRB(
Math.Min(_anchor.X, e.X), Math.Min(_anchor.Y, e.Y),
Math.Max(_anchor.X, e.X), Math.Max(_anchor.Y, e.Y));
Invalidate();
}
base.OnMouseMove(e);
}
protected override void OnMouseUp(MouseEventArgs e)
{
if (!_dragging) return;
_dragging = false;
// A sub-8px drag is a slip, not a selection; stay open to try again.
if (_selection.Width < 8 || _selection.Height < 8)
{
_selection = Rectangle.Empty;
Invalidate();
return;
}
Rectangle crop = Rectangle.Intersect(_selection,
new Rectangle(0, 0, _frozen.Width, _frozen.Height));
Result = _frozen.Clone(crop, _frozen.PixelFormat);
DialogResult = DialogResult.OK;
Close();
base.OnMouseUp(e);
}
protected override void OnPaint(PaintEventArgs e)
{
e.Graphics.DrawImageUnscaled(_frozen, 0, 0);
// Everything outside the selection under a dark wash; the selection
// stays at full brightness with an accent border, so what will be
// read is exactly what looks lit.
using (SolidBrush dim = new SolidBrush(Color.FromArgb(120, 0, 0, 0)))
{
if (_selection.IsEmpty)
{
e.Graphics.FillRectangle(dim, ClientRectangle);
}
else
{
Rectangle s = _selection;
e.Graphics.FillRectangle(dim, 0, 0, Width, s.Top);
e.Graphics.FillRectangle(dim, 0, s.Bottom, Width, Height - s.Bottom);
e.Graphics.FillRectangle(dim, 0, s.Top, s.Left, s.Height);
e.Graphics.FillRectangle(dim, s.Right, s.Top, Width - s.Right, s.Height);
using (Pen accent = new Pen(Th.T.Accent, 2f))
e.Graphics.DrawRectangle(accent, s.Left, s.Top, s.Width - 1, s.Height - 1);
}
}
if (_selection.IsEmpty)
{
string hint = "Drag a rectangle over the text to grab - Esc cancels";
using (Font f = new Font("Segoe UI", 12F, FontStyle.Bold))
{
Size sz = TextRenderer.MeasureText(hint, f);
// Centered on the monitor holding the pointer, not on the
// virtual desktop: across two identical displays the latter
// puts the hint half on each side of the bezel.
Rectangle mon = Screen.FromPoint(Cursor.Position).Bounds;
Point p = new Point(
mon.Left - _screenBounds.Left + (mon.Width - sz.Width) / 2,
mon.Top - _screenBounds.Top + Dpi.S(40));
Rectangle pill = new Rectangle(p.X - Dpi.S(14), p.Y - Dpi.S(8),
sz.Width + Dpi.S(28), sz.Height + Dpi.S(16));
Draw.FillBorderRound(e.Graphics, pill, Dpi.S(6), Th.T.Panel, Th.T.Border);
TextRenderer.DrawText(e.Graphics, hint, f, p, Th.T.Txt);
}
}
}
protected override void Dispose(bool disposing)
{
// _frozen is owned by the caller (tests reuse it); Result is handed
// off. Nothing to dispose beyond the base.
base.Dispose(disposing);
}
}
// Shows what OCR read, in an editable box, on top of having put it on the
// clipboard. Seeing the text is what makes a misread zero obvious before
// it is pasted anywhere that matters; being editable means it can be fixed
// right here and re-copied without a round trip through another editor.
public class OcrResultForm : Form
{
ScrollAwareTextBox _box;
InputHost _host;
ThemedScrollBar _scroll;
bool _syncing;
ThemedButton _copy;
ThemedButton _close;
Label _note;
Font _uiFont;
Font _monoFont;
public OcrResultForm(string text)
{
Text = "OCR result";
AutoScaleMode = AutoScaleMode.None;
FormBorderStyle = FormBorderStyle.Sizable;
StartPosition = FormStartPosition.CenterParent;
MinimizeBox = false;
ShowInTaskbar = false;
ShowIcon = false; // the stock WinForms icon, not the brand mark
ClientSize = new Size(Dpi.S(560), Dpi.S(360));
MinimumSize = new Size(Dpi.S(380), Dpi.S(240));
_uiFont = new Font("Segoe UI", 9F);
Font = _uiFont;
KeyPreview = true;
BackColor = Th.T.Panel2;
_box = new ScrollAwareTextBox();
_box.Multiline = true;
_box.AcceptsReturn = true;
_box.WordWrap = false;
_box.ScrollBars = ScrollBars.None;
_box.BorderStyle = BorderStyle.None;
_monoFont = new Font("Consolas", 10F);
_box.Font = _monoFont;
_box.Text = text;
_box.SelectionStart = 0;
_host = new InputHost(_box, Dpi.S(6), Dpi.S(5));
_host.Dock = DockStyle.Fill;
_scroll = new ThemedScrollBar();
_scroll.Dock = DockStyle.Right;
_host.Controls.Add(_scroll);
_box.ViewChanged += delegate(object s, EventArgs e) { SyncScroll(); };
_box.TextChanged += delegate(object s, EventArgs e) { SyncScroll(); };
_scroll.UserScrolled += delegate(object s, EventArgs e)
{
if (_syncing) return;
_syncing = true;
_box.ScrollToLine(_scroll.Value);
_syncing = false;
};
Panel bottom = new Panel();
bottom.Dock = DockStyle.Bottom;
bottom.Height = Dpi.S(44);
bottom.BackColor = Th.T.Panel2;
_note = new Label();
_note.AutoSize = false;
_note.TextAlign = ContentAlignment.MiddleLeft;
_note.ForeColor = Th.T.TxtDim;
_note.BackColor = Th.T.Panel2;
_note.Text = "Already on the clipboard. Check digits, especially zeros.";
_copy = new ThemedButton();
_copy.Primary = true;
_copy.Text = "Copy";
_copy.Click += delegate(object s, EventArgs e)
{
_note.Text = Clip.Put(_box.Text)
? "Copied."
: "Clipboard is locked by another app.";
};
_close = new ThemedButton();
_close.Text = "Close";
_close.Click += delegate(object s, EventArgs e) { Close(); };
bottom.Controls.Add(_note);
bottom.Controls.Add(_copy);
bottom.Controls.Add(_close);
bottom.Resize += delegate(object s, EventArgs e)
{
int h = Dpi.S(28);
int y = (bottom.Height - h) / 2;
_close.SetBounds(bottom.Width - Dpi.S(86), y, Dpi.S(74), h);
_copy.SetBounds(_close.Left - Dpi.S(80), y, Dpi.S(74), h);
_note.SetBounds(Dpi.S(12), y, Math.Max(Dpi.S(60), _copy.Left - Dpi.S(24)), h);
};
Panel content = new Panel();
content.Dock = DockStyle.Fill;
content.Padding = new Padding(Dpi.S(12), Dpi.S(12), Dpi.S(12), Dpi.S(4));
content.BackColor = Th.T.Panel2;
content.Controls.Add(_host);
Controls.Add(content);
Controls.Add(bottom);
}
protected override void OnHandleCreated(EventArgs e)
{
base.OnHandleCreated(e);
OsChrome.ApplyTitleBar(this);
}
protected override void OnShown(EventArgs e)
{
base.OnShown(e);
SyncScroll();
}
void SyncScroll()
{
if (_syncing) return;
_syncing = true;
_scroll.Configure(_box.VisualLineCount, _box.VisibleLines, _box.FirstVisibleLine);
_syncing = false;
}
protected override void OnKeyDown(KeyEventArgs e)
{
if (e.KeyCode == Keys.Escape) { Close(); return; }
base.OnKeyDown(e);
}
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
// After the base call, never before: the controls still reference
// these while they are being torn down. Both were constructed here
// rather than inherited, so nothing else will free them.
if (disposing)
{
if (_uiFont != null) { _uiFont.Dispose(); _uiFont = null; }
if (_monoFont != null) { _monoFont.Dispose(); _monoFont = null; }
}
}
}
}