-
Notifications
You must be signed in to change notification settings - Fork 8k
Expand file tree
/
Copy pathCommon.cs
More file actions
1655 lines (1403 loc) · 59.1 KB
/
Common.cs
File metadata and controls
1655 lines (1403 loc) · 59.1 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
// Copyright (c) Microsoft Corporation
// The Microsoft Corporation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Drawing;
using System.Drawing.Imaging;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using Microsoft.PowerToys.Settings.UI.Library;
using MouseWithoutBorders.Class;
using MouseWithoutBorders.Exceptions;
using Clipboard = MouseWithoutBorders.Core.Clipboard;
using SocketStatus = MouseWithoutBorders.Class.SocketStatus;
using Thread = MouseWithoutBorders.Core.Thread;
// Log is enough
[module: SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Scope = "member", Target = "MouseWithoutBorders.Common.#CheckClipboard()", Justification = "Dotnet port with style preservation")]
[module: SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Scope = "member", Target = "MouseWithoutBorders.Common.#CheckForDesktopSwitchEvent(System.Boolean)", Justification = "Dotnet port with style preservation")]
[module: SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Scope = "member", Target = "MouseWithoutBorders.Common.#SetAsStartupItem(System.Boolean)", Justification = "Dotnet port with style preservation")]
[module: SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Scope = "member", Target = "MouseWithoutBorders.Common.#HelperThread()", Justification = "Dotnet port with style preservation")]
[module: SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Scope = "member", Target = "MouseWithoutBorders.Common.#GetMyStorageDir()", Justification = "Dotnet port with style preservation")]
[module: SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Scope = "member", Target = "MouseWithoutBorders.Common.#MouseEvent(MouseWithoutBorders.MOUSEDATA)", Justification = "Dotnet port with style preservation")]
[module: SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Scope = "member", Target = "MouseWithoutBorders.Common.#KeybdEvent(MouseWithoutBorders.KEYBDDATA)", Justification = "Dotnet port with style preservation")]
[module: SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Scope = "member", Target = "MouseWithoutBorders.Common.#ImpersonateLoggedOnUserAndDoSomething(System.Threading.ThreadStart)", Justification = "Dotnet port with style preservation")]
[module: SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Scope = "member", Target = "MouseWithoutBorders.Common.#StartMouseWithoutBordersService()", Justification = "Dotnet port with style preservation")]
[module: SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Scope = "member", Target = "MouseWithoutBorders.Common.#HookClipboard()", Justification = "Dotnet port with style preservation")]
[module: SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Scope = "member", Target = "MouseWithoutBorders.Common.#ReceiveClipboardData(MouseWithoutBorders.DATA,System.Boolean)", Justification = "Dotnet port with style preservation")]
[module: SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Scope = "member", Target = "MouseWithoutBorders.Common.#ReceiverCallback(System.Object)", Justification = "Dotnet port with style preservation")]
[module: SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Scope = "member", Target = "MouseWithoutBorders.Common.#ConnectAndGetData(System.Object)", Justification = "Dotnet port with style preservation")]
[module: SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Scope = "member", Target = "MouseWithoutBorders.Common.#CheckNewVersion()", Justification = "Dotnet port with style preservation")]
[module: SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Scope = "member", Target = "MouseWithoutBorders.Common.#StartServiceAndSendLogoffSignal()", Justification = "Dotnet port with style preservation")]
[module: SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Scope = "member", Target = "MouseWithoutBorders.Common.#GetScreenConfig()", Justification = "Dotnet port with style preservation")]
[module: SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Scope = "member", Target = "MouseWithoutBorders.Common.#CaptureScreen()", Justification = "Dotnet port with style preservation")]
[module: SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Scope = "member", Target = "MouseWithoutBorders.Common.#InitEncryption()", Justification = "Dotnet port with style preservation")]
[module: SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Scope = "member", Target = "MouseWithoutBorders.Common.#ToggleIcon()", Justification = "Dotnet port with style preservation")]
[module: SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Scope = "member", Target = "MouseWithoutBorders.Common.#GetNameAndIPAddresses()", Justification = "Dotnet port with style preservation")]
[module: SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Scope = "member", Target = "MouseWithoutBorders.Common.#Cleanup()", Justification = "Dotnet port with style preservation")]
[module: SuppressMessage("Microsoft.Maintainability", "CA1506:AvoidExcessiveClassCoupling", Scope = "type", Target = "MouseWithoutBorders.Common", Justification = "Dotnet port with style preservation")]
[module: SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Scope = "member", Target = "MouseWithoutBorders.Common.#ConnectAndGetData(System.Object)", Justification = "Dotnet port with style preservation")]
[module: SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Scope = "member", Target = "MouseWithoutBorders.Common.#ProcessPackage(MouseWithoutBorders.DATA)", Justification = "Dotnet port with style preservation")]
[module: SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Scope = "member", Target = "MouseWithoutBorders.Common.#SetOEMBackground(System.Boolean)", Justification = "Dotnet port with style preservation")]
[module: SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Scope = "member", Target = "MouseWithoutBorders.Common.#get_Machine_Pool()", Justification = "Dotnet port with style preservation")]
[module: SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Scope = "member", Target = "MouseWithoutBorders.Common.#SetOEMBackground(System.Boolean,System.String)", Justification = "Dotnet port with style preservation")]
[module: SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Scope = "member", Target = "MouseWithoutBorders.Common.#GetNewImageAndSaveTo(System.String,System.String)", Justification = "Dotnet port with style preservation")]
[module: SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Scope = "member", Target = "MouseWithoutBorders.Common.#CreateLowIntegrityProcess(System.String,System.String,System.Int32)", Justification = "Dotnet port with style preservation")]
[module: SuppressMessage("Microsoft.Usage", "CA1806:DoNotIgnoreMethodResults", Scope = "member", Target = "MouseWithoutBorders.Common.#LogAll()", MessageId = "System.String.Format(System.IFormatProvider,System.String,System.Object[])", Justification = "Dotnet port with style preservation")]
[module: SuppressMessage("Microsoft.Usage", "CA1806:DoNotIgnoreMethodResults", Scope = "member", Target = "MouseWithoutBorders.Common.#CheckForDesktopSwitchEvent(System.Boolean)", MessageId = "MouseWithoutBorders.NativeMethods.SendMessage(System.IntPtr,System.Int32,System.IntPtr,System.IntPtr)", Justification = "Dotnet port with style preservation")]
[module: SuppressMessage("Microsoft.Usage", "CA1806:DoNotIgnoreMethodResults", Scope = "member", Target = "MouseWithoutBorders.Common.#DragDropStep04()", MessageId = "MouseWithoutBorders.NativeMethods.SendMessage(System.IntPtr,System.Int32,System.IntPtr,System.IntPtr)", Justification = "Dotnet port with style preservation")]
[module: SuppressMessage("Microsoft.Usage", "CA1806:DoNotIgnoreMethodResults", Scope = "member", Target = "MouseWithoutBorders.Common.#CreateLowIntegrityProcess(System.String,System.String,System.Int32)", MessageId = "MouseWithoutBorders.NativeMethods.WaitForSingleObject(System.IntPtr,System.Int32)", Justification = "Dotnet port with style preservation")]
[module: SuppressMessage("Microsoft.Usage", "CA1806:DoNotIgnoreMethodResults", Scope = "member", Target = "MouseWithoutBorders.Common.#GetText(System.IntPtr)", MessageId = "MouseWithoutBorders.NativeMethods.GetWindowText(System.IntPtr,System.Text.StringBuilder,System.Int32)", Justification = "Dotnet port with style preservation")]
[module: SuppressMessage("Microsoft.Usage", "CA1806:DoNotIgnoreMethodResults", Scope = "member", Target = "MouseWithoutBorders.Common.#ImpersonateLoggedOnUserAndDoSomething(System.Threading.ThreadStart)", MessageId = "MouseWithoutBorders.NativeMethods.WTSQueryUserToken(System.UInt32,System.IntPtr@)", Justification = "Dotnet port with style preservation")]
[module: SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Scope = "member", Target = "MouseWithoutBorders.Common.#CreateLowIntegrityProcess(System.String,System.String,System.Int32,System.Boolean,System.Int64)", Justification = "Dotnet port with style preservation")]
[module: SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Scope = "member", Target = "MouseWithoutBorders.Common.#CreateProcessInInputDesktopSession(System.String,System.String,System.String,System.Boolean,System.Int16)", Justification = "Dotnet port with style preservation")]
[module: SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Scope = "member", Target = "MouseWithoutBorders.Common.#SkSend(MouseWithoutBorders.DATA,System.Boolean,System.Int32)", Justification = "Dotnet port with style preservation")]
[module: SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Scope = "member", Target = "MouseWithoutBorders.Common.#ReceiveClipboardDataUsingTCP(MouseWithoutBorders.DATA,System.Boolean,System.Net.Sockets.Socket)", Justification = "Dotnet port with style preservation")]
[module: SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Scope = "member", Target = "MouseWithoutBorders.Common.#UpdateMachineMatrix(MouseWithoutBorders.DATA)", Justification = "Dotnet port with style preservation")]
[module: SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Scope = "member", Target = "MouseWithoutBorders.Common.#ReopenSockets(System.Boolean)", Justification = "Dotnet port with style preservation")]
// <summary>
// Most of the helper methods.
// </summary>
// <history>
// 2008 created by Truong Do (ductdo).
// 2009-... modified by Truong Do (TruongDo).
// 2023- Included in PowerToys.
// </history>
namespace MouseWithoutBorders.Core;
internal static class Common
{
private static InputHook hook;
private static FrmMatrix matrixForm;
private static FrmInputCallback inputCallbackForm;
private static FrmAbout aboutForm;
#pragma warning disable SA1307 // Accessible fields should begin with upper-case letter
internal static Thread helper;
internal static int screenWidth;
internal static int screenHeight;
#pragma warning restore SA1307
private static int lastX;
private static int lastY;
private static bool mainFormVisible = true;
private static bool runOnLogonDesktop;
private static bool runOnScrSaverDesktop;
#pragma warning disable SA1307 // Accessible fields should begin with upper-case letter
internal static int[] toggleIcons;
internal static int toggleIconsIndex;
#pragma warning restore SA1307
internal const int TOGGLE_ICONS_SIZE = 4;
internal const int ICON_ONE = 0;
internal const int ICON_ALL = 1;
internal const int ICON_SMALL_CLIPBOARD = 2;
internal const int ICON_BIG_CLIPBOARD = 3;
internal const int ICON_ERROR = 4;
internal const int JUST_GOT_BACK_FROM_SCREEN_SAVER = 9999;
internal const int NETWORK_STREAM_BUF_SIZE = 1024 * 1024;
internal static readonly EventWaitHandle EvSwitch = new(false, EventResetMode.AutoReset);
private static Point lastPos;
#pragma warning disable SA1307 // Accessible fields should begin with upper-case names
internal static int switchCount;
#pragma warning restore SA1307
private static long lastReconnectByHotKeyTime;
#pragma warning disable SA1307 // Accessible fields should begin with upper-case names
internal static int tcpPort;
#pragma warning restore SA1307
private static bool secondOpenSocketTry;
private static string binaryName;
internal static Process CurrentProcess { get; set; }
internal static bool HotkeyMatched(int vkCode, bool winDown, bool ctrlDown, bool altDown, bool shiftDown, HotkeySettings hotkey)
{
return !hotkey.IsEmpty() && (vkCode == hotkey.Code) && (!hotkey.Win || winDown) && (!hotkey.Alt || altDown) && (!hotkey.Shift || shiftDown) && (!hotkey.Ctrl || ctrlDown);
}
internal static string BinaryName
{
get => Common.binaryName;
set => Common.binaryName = value;
}
internal static bool SecondOpenSocketTry
{
get => Common.secondOpenSocketTry;
set => Common.secondOpenSocketTry = value;
}
internal static long LastReconnectByHotKeyTime
{
get => Common.lastReconnectByHotKeyTime;
set => Common.lastReconnectByHotKeyTime = value;
}
internal static int SwitchCount
{
get => Common.switchCount;
set => Common.switchCount = value;
}
internal static Point LastPos
{
get => Common.lastPos;
set => Common.lastPos = value;
}
internal static FrmAbout AboutForm
{
get => Common.aboutForm;
set => Common.aboutForm = value;
}
internal static FrmInputCallback InputCallbackForm
{
get => Common.inputCallbackForm;
set => Common.inputCallbackForm = value;
}
internal static int PaintCount { get; set; }
internal static bool RunOnScrSaverDesktop
{
get => Common.runOnScrSaverDesktop;
set => Common.runOnScrSaverDesktop = value;
}
internal static bool RunOnLogonDesktop
{
get => Common.runOnLogonDesktop;
set => Common.runOnLogonDesktop = value;
}
internal static bool RunWithNoAdminRight { get; set; }
internal static int LastX
{
get => Common.lastX;
set => Common.lastX = value;
}
internal static int LastY
{
get => Common.lastY;
set => Common.lastY = value;
}
internal static int[] ToggleIcons => Common.toggleIcons;
internal static int ScreenHeight => Common.screenHeight;
internal static int ScreenWidth => Common.screenWidth;
internal static bool Is64bitOS
{
get; set;
// set { Common.is64bitOS = value; }
}
internal static int ToggleIconsIndex
{
// get { return Common.toggleIconsIndex; }
set => Common.toggleIconsIndex = value;
}
internal static InputHook Hook
{
get => Common.hook;
set => Common.hook = value;
}
internal static SocketStuff Sk { get; set; }
internal static FrmScreen MainForm { get; set; }
internal static FrmMouseCursor MouseCursorForm { get; set; }
internal static FrmMatrix MatrixForm
{
get => Common.matrixForm;
set => Common.matrixForm = value;
}
internal static ID DesMachineID
{
get => MachineStuff.desMachineID;
set
{
MachineStuff.desMachineID = value;
MachineStuff.DesMachineName = MachineStuff.NameFromID(MachineStuff.desMachineID);
}
}
internal static ID MachineID => (ID)Setting.Values.MachineId;
internal static string MachineName { get; set; }
internal static bool MainFormVisible
{
get => Common.mainFormVisible;
set => Common.mainFormVisible = value;
}
internal static Mutex SocketMutex { get; set; } // Synchronization between MouseWithoutBorders running in different desktops
// TODO: For telemetry only, to be removed.
private static int socketMutexBalance;
internal static void ReleaseSocketMutex()
{
if (SocketMutex != null)
{
Logger.LogDebug("SOCKET MUTEX BEGIN RELEASE.");
try
{
_ = Interlocked.Decrement(ref socketMutexBalance);
SocketMutex.ReleaseMutex();
}
catch (ApplicationException e)
{
// The current thread does not own the mutex, the thread acquired it will own it.
Logger.TelemetryLogTrace($"{nameof(ReleaseSocketMutex)}: {e.Message}. {Thread.CurrentThread.ManagedThreadId}/{UIThreadID}.", SeverityLevel.Warning);
}
Logger.LogDebug("SOCKET MUTEX RELEASED.");
}
else
{
Logger.LogDebug("SOCKET MUTEX NULL.");
}
}
internal static void AcquireSocketMutex()
{
if (SocketMutex != null)
{
Logger.LogDebug("SOCKET MUTEX BEGIN WAIT.");
int waitTimeout = 60000; // TcpListener.Stop may take very long to complete for some reason.
int socketMutexBalance = int.MinValue;
bool acquireMutex = ExecuteAndTrace(
"Waiting for sockets to close",
() =>
{
socketMutexBalance = Interlocked.Increment(ref Common.socketMutexBalance);
_ = SocketMutex.WaitOne(waitTimeout); // The app now requires .Net 4.0. Note: .Net20RTM does not have the one-parameter version of the API.
},
TimeSpan.FromSeconds(5));
// Took longer than expected.
if (!acquireMutex)
{
Process[] ps = Process.GetProcessesByName(Common.BinaryName);
Logger.TelemetryLogTrace($"Balance: {socketMutexBalance}, Active: {WinAPI.IsMyDesktopActive()}, Sid/Console: {Process.GetCurrentProcess().SessionId}/{NativeMethods.WTSGetActiveConsoleSessionId()}, Desktop/Input: {WinAPI.GetMyDesktop()}/{WinAPI.GetInputDesktop()}, count: {ps?.Length}.", SeverityLevel.Warning);
}
Logger.LogDebug("SOCKET MUTEX ENDED.");
}
else
{
Logger.LogDebug("SOCKET MUTEX NULL.");
}
}
internal static bool BlockingUI { get; private set; }
internal static bool ExecuteAndTrace(string actionName, Action action, TimeSpan timeout, bool restart = false)
{
bool rv = true;
Logger.LogDebug(actionName);
bool done = false;
BlockingUI = true;
if (restart)
{
Common.MainForm.Text = Setting.Values.MyIdEx;
/* closesocket() rarely gets stuck for some reason inside ntdll!ZwClose ...=>... afd!AfdCleanupCore.
* There is no good workaround for it so far, still working with [Winsock 2.0 Discussions] to address the issue.
* */
new Thread(
() =>
{
for (int i = 0; i < timeout.TotalSeconds; i++)
{
Thread.Sleep(1000);
if (done)
{
return;
}
}
Logger.TelemetryLogTrace($"[{actionName}] took more than {(long)timeout.TotalSeconds}, restarting the process.", SeverityLevel.Warning, true);
string desktop = WinAPI.GetMyDesktop();
MachineStuff.oneInstanceCheck?.Close();
_ = Process.Start(Application.ExecutablePath, desktop);
Logger.LogDebug($"Started on desktop {desktop}");
Process.GetCurrentProcess().KillProcess(true);
},
$"{actionName} watchdog").Start();
}
Stopwatch timer = Stopwatch.StartNew();
try
{
action();
}
finally
{
done = true;
BlockingUI = false;
if (restart)
{
Common.MainForm.Text = Setting.Values.MyID;
}
timer.Stop();
if (timer.Elapsed > timeout)
{
rv = false;
if (!restart)
{
Logger.TelemetryLogTrace($"[{actionName}] took more than {(long)timeout.TotalSeconds}: {(long)timer.Elapsed.TotalSeconds}.", SeverityLevel.Warning);
}
}
}
return rv;
}
internal static byte[] GetBytes(string st)
{
return ASCIIEncoding.ASCII.GetBytes(st);
}
internal static string GetString(byte[] bytes)
{
return ASCIIEncoding.ASCII.GetString(bytes);
}
internal static byte[] GetBytesU(string st)
{
return ASCIIEncoding.Unicode.GetBytes(st);
}
internal static string GetStringU(byte[] bytes)
{
return ASCIIEncoding.Unicode.GetString(bytes);
}
internal static int UIThreadID { get; set; }
internal static void DoSomethingInUIThread(Action action, bool blocking = false)
{
InvokeInFormThread(MainForm, UIThreadID, action, blocking);
}
internal static int InputCallbackThreadID { get; set; }
internal static void DoSomethingInTheInputCallbackThread(Action action, bool blocking = true)
{
InvokeInFormThread(InputCallbackForm, InputCallbackThreadID, action, blocking);
}
private static void InvokeInFormThread(System.Windows.Forms.Form form, int threadId, Action action, bool blocking)
{
if (form != null)
{
int currentThreadId = Thread.CurrentThread.ManagedThreadId;
if (currentThreadId == threadId)
{
action();
}
else
{
bool done = false;
try
{
Action callback = () =>
{
try
{
action();
}
catch (Exception e)
{
Logger.Log(e);
}
finally
{
done = true;
}
};
_ = form.BeginInvoke(callback);
}
catch (Exception e)
{
done = true;
Logger.Log(e);
}
while (blocking && !done)
{
Thread.Sleep(16);
if (currentThreadId == UIThreadID || currentThreadId == InputCallbackThreadID)
{
Application.DoEvents();
}
}
}
}
}
private static readonly Lock InputSimulationLock = new();
internal static void DoSomethingInTheInputSimulationThread(ThreadStart target)
{
/*
* For some reason, SendInput may hit deadlock if it is called in the InputHookProc thread.
* For now leave it as is in the caller thread which is the socket receiver thread.
* */
// SendInput is thread-safe but few users seem to hit a deadlock occasionally, probably a Windows bug.
lock (InputSimulationLock)
{
target();
}
}
internal static void SendPackage(ID des, PackageType packageType)
{
DATA package = new();
package.Type = packageType;
package.Des = des;
package.MachineName = MachineName;
SkSend(package, null, false);
}
internal static void SendHeartBeat(bool initial = false)
{
SendPackage(ID.ALL, initial && Encryption.GeneratedKey ? PackageType.Heartbeat_ex : PackageType.Heartbeat);
}
private static long lastSendNextMachine;
internal static void SendNextMachine(ID hostMachine, ID nextMachine, Point requestedXY)
{
Logger.LogDebug($"SendNextMachine: Host machine: {hostMachine}, Next machine: {nextMachine}, Requested XY: {requestedXY}");
if (GetTick() - lastSendNextMachine < 100)
{
Logger.LogDebug("Machine switching in progress."); // "Move Mouse relatively" mode, slow machine/network, quick/busy hand.
return;
}
lastSendNextMachine = GetTick();
DATA package = new();
package.Type = PackageType.NextMachine;
package.Des = hostMachine;
package.Md.X = requestedXY.X;
package.Md.Y = requestedXY.Y;
package.Md.WheelDelta = (int)nextMachine;
SkSend(package, null, false);
Logger.LogDebug("SendNextMachine done.");
}
private static ulong lastInputEventCount;
private static ulong lastRealInputEventCount;
internal static void SendAwakeBeat()
{
if (!Common.RunOnLogonDesktop && !Common.RunOnScrSaverDesktop && WinAPI.IsMyDesktopActive() &&
Setting.Values.BlockScreenSaver && lastRealInputEventCount != Event.RealInputEventCount)
{
SendPackage(ID.ALL, PackageType.Awake);
}
else
{
SendHeartBeat();
}
lastInputEventCount = Event.InputEventCount;
lastRealInputEventCount = Event.RealInputEventCount;
}
internal static void HumanBeingDetected()
{
if (lastInputEventCount == Event.InputEventCount)
{
if (!Common.RunOnLogonDesktop && !Common.RunOnScrSaverDesktop && WinAPI.IsMyDesktopActive())
{
PokeMyself();
}
}
lastInputEventCount = Event.InputEventCount;
}
private static void PokeMyself()
{
int x, y = 0;
for (int i = 0; i < 10; i++)
{
x = Encryption.Ran.Next(-9, 10);
InputSimulation.MoveMouseRelative(x, y);
Thread.Sleep(50);
InputSimulation.MoveMouseRelative(-x, -y);
Thread.Sleep(50);
if (lastInputEventCount != Event.InputEventCount)
{
break;
}
}
}
internal static void InitLastInputEventCount()
{
lastInputEventCount = Event.InputEventCount;
lastRealInputEventCount = Event.RealInputEventCount;
}
internal static void SendHello()
{
SendPackage(ID.ALL, PackageType.Hello);
}
/*
internal static void SendHi()
{
SendPackage(IP.ALL, PackageType.hi);
}
* */
internal static void SendByeBye()
{
Logger.LogDebug($"{nameof(SendByeBye)}");
SendPackage(ID.ALL, PackageType.ByeBye);
}
internal static void SendClipboardBeat()
{
SendPackage(ID.ALL, PackageType.Clipboard);
}
internal static void ProcessByeByeMessage(DATA package)
{
if (package.Src == MachineStuff.desMachineID)
{
MachineStuff.SwitchToMachine(MachineName.Trim());
}
_ = MachineStuff.RemoveDeadMachines(package.Src);
}
internal static long GetTick() // ms
{
return DateTime.Now.Ticks / 10000;
}
internal static void SetToggleIcon(int[] toggleIcons)
{
Logger.LogDebug($"{nameof(SetToggleIcon)}: {toggleIcons?.FirstOrDefault()}");
Common.toggleIcons = toggleIcons;
toggleIconsIndex = 0;
}
internal static string CaptureScreen()
{
try
{
string fileName = GetMyStorageDir() + @"ScreenCaptureByMouseWithoutBorders.png";
int w = MachineStuff.desktopBounds.Right - MachineStuff.desktopBounds.Left;
int h = MachineStuff.desktopBounds.Bottom - MachineStuff.desktopBounds.Top;
Bitmap bm = new(w, h);
Graphics g = Graphics.FromImage(bm);
Size s = new(w, h);
g.CopyFromScreen(MachineStuff.desktopBounds.Left, MachineStuff.desktopBounds.Top, 0, 0, s);
bm.Save(fileName, ImageFormat.Png);
bm.Dispose();
return fileName;
}
catch (Exception e)
{
Logger.Log(e);
return null;
}
}
private static void PrepareScreenCapture()
{
Common.DoSomethingInUIThread(() =>
{
if (!DragDrop.MouseDown && Helper.SendMessageToHelper(0x401, IntPtr.Zero, IntPtr.Zero) > 0)
{
Common.MMSleep(0.2);
InputSimulation.SendKey(new KEYBDDATA() { wVk = (int)VK.SNAPSHOT });
InputSimulation.SendKey(new KEYBDDATA() { dwFlags = (int)WM.LLKHF.UP, wVk = (int)VK.SNAPSHOT });
Logger.LogDebug("PrepareScreenCapture: SNAPSHOT simulated.");
_ = NativeMethods.MoveWindow(
(IntPtr)NativeMethods.FindWindow(null, Helper.HELPER_FORM_TEXT),
MachineStuff.DesktopBounds.Left,
MachineStuff.DesktopBounds.Top,
MachineStuff.DesktopBounds.Right - MachineStuff.DesktopBounds.Left,
MachineStuff.DesktopBounds.Bottom - MachineStuff.DesktopBounds.Top,
false);
_ = Helper.SendMessageToHelper(0x406, IntPtr.Zero, IntPtr.Zero, false);
}
else
{
Logger.Log("PrepareScreenCapture: Validation failed.");
}
});
}
internal static void OpenImage(string file)
{
// We want to run mspaint under the user account who ran explorer.exe (who logged in this current input desktop)
// ImpersonateLoggedOnUserAndDoSomething(delegate()
// {
// Process.Start("explorer", "\"" + file + "\"");
// });
_ = Launch.CreateProcessInInputDesktopSession(
"\"" + Environment.ExpandEnvironmentVariables(@"%SystemRoot%\System32\Mspaint.exe") +
"\"",
"\"" + file + "\"",
WinAPI.GetInputDesktop(),
1);
// CreateNormalIntegrityProcess(Environment.ExpandEnvironmentVariables(@"%SystemRoot%\System32\Mspaint.exe") +
// " \"" + file + "\"");
// We don't want to run mspaint as local system account
/*
ProcessStartInfo s = new ProcessStartInfo(
Environment.ExpandEnvironmentVariables(@"%SystemRoot%\System32\Mspaint.exe"),
"\"" + file + "\"");
s.WindowStyle = ProcessWindowStyle.Maximized;
Process.Start(s);
* */
}
internal static void SendImage(string machine, string file)
{
Clipboard.LastDragDropFile = file;
// Send ClipboardCapture
if (machine.Equals("All", StringComparison.OrdinalIgnoreCase))
{
SendPackage(ID.ALL, PackageType.ClipboardCapture);
}
else
{
ID id = MachineStuff.MachinePool.ResolveID(machine);
if (id != ID.NONE)
{
SendPackage(id, PackageType.ClipboardCapture);
}
}
}
internal static void SendImage(ID src, string file)
{
Clipboard.LastDragDropFile = file;
// Send ClipboardCapture
SendPackage(src, PackageType.ClipboardCapture);
}
internal static void ShowToolTip(string tip, int timeOutInMilliseconds = 5000, ToolTipIcon icon = ToolTipIcon.Info, bool showBalloonTip = true, bool forceEvenIfHidingOldUI = false)
{
if (!Common.RunOnLogonDesktop && !Common.RunOnScrSaverDesktop)
{
DoSomethingInUIThread(() =>
{
if (Setting.Values.FirstRun)
{
MachineStuff.Settings?.ShowTip(icon, tip, timeOutInMilliseconds);
}
Common.MatrixForm?.ShowTip(icon, tip, timeOutInMilliseconds);
if (showBalloonTip)
{
if (MainForm != null)
{
MainForm.ShowToolTip(tip, timeOutInMilliseconds, forceEvenIfHidingOldUI: forceEvenIfHidingOldUI);
}
else
{
Logger.Log(tip);
}
}
});
}
}
private static FrmMessage topMostMessageForm;
internal static void ToggleShowTopMostMessage(string text, string bigText, int timeOut)
{
DoSomethingInUIThread(() =>
{
if (topMostMessageForm == null)
{
topMostMessageForm = new FrmMessage(text, bigText, timeOut);
topMostMessageForm.Show();
}
else
{
FrmMessage currentMessageForm = topMostMessageForm;
topMostMessageForm = null;
currentMessageForm.Close();
}
});
}
internal static void HideTopMostMessage()
{
DoSomethingInUIThread(() =>
{
topMostMessageForm?.Close();
});
}
internal static void NullTopMostMessage()
{
DoSomethingInUIThread(() =>
{
if (topMostMessageForm != null)
{
topMostMessageForm = null;
}
});
}
internal static bool IsTopMostMessageNotNull()
{
return topMostMessageForm != null;
}
private static bool TestSend(TcpSk t)
{
ID remoteMachineID;
if (t.Status == SocketStatus.Connected)
{
try
{
DATA package = new();
package.Type = PackageType.Hi;
package.Des = remoteMachineID = (ID)t.MachineId;
package.MachineName = MachineName;
_ = Sk.TcpSend(t, package);
t.EncryptedStream?.Flush();
return true;
}
catch (ExpectedSocketException)
{
t.BackingSocket = null; // To be removed at CloseAnUnusedSocket()
}
}
t.Status = SocketStatus.SendError;
return false;
}
internal static bool IsConnectedTo(ID remoteMachineID)
{
bool updateClientSockets = false;
if (remoteMachineID == MachineID)
{
return true;
}
SocketStuff sk = Common.Sk;
if (sk != null)
{
lock (sk.TcpSocketsLock)
{
if (sk.TcpSockets != null)
{
foreach (TcpSk t in sk.TcpSockets)
{
if (t.Status == SocketStatus.Connected && (uint)remoteMachineID == t.MachineId)
{
if (TestSend(t))
{
return true;
}
else
{
updateClientSockets = true;
}
}
}
}
}
}
if (updateClientSockets)
{
MachineStuff.UpdateClientSockets(nameof(IsConnectedTo));
}
return false;
}
#if DEBUG
private static long minSendTime = long.MaxValue;
private static long avgSendTime;
private static long maxSendTime;
private static long totalSendCount;
private static long totalSendTime;
#endif
internal static void SkSend(DATA data, uint? exceptDes, bool includeHandShakingSockets)
{
bool connected = false;
SocketStuff sk = Sk;
if (sk != null)
{
#if DEBUG
long startStop = DateTime.Now.Ticks;
totalSendCount++;
#endif
try
{
data.Id = Interlocked.Increment(ref Package.PackageID);
bool updateClientSockets = false;
lock (sk.TcpSocketsLock)
{
foreach (TcpSk t in sk.TcpSockets)
{
if (t != null && t.BackingSocket != null && (t.Status == SocketStatus.Connected || (t.Status == SocketStatus.Handshaking && includeHandShakingSockets)))
{
if (t.MachineId == (uint)data.Des || (data.Des == ID.ALL && t.MachineId != exceptDes && MachineStuff.InMachineMatrix(t.MachineName)))
{
try
{
sk.TcpSend(t, data);
if (data.Des != ID.ALL)
{
connected = true;
}
}
catch (ExpectedSocketException)
{
t.BackingSocket = null; // To be removed at CloseAnUnusedSocket()
updateClientSockets = true;
}
catch (Exception e)
{
Logger.Log(e);
t.BackingSocket = null; // To be removed at CloseAnUnusedSocket()
updateClientSockets = true;
}
}
}
}
}
if (!connected && data.Des != ID.ALL)
{
Logger.LogDebug("********** No active connection found for the remote machine! **********" + data.Des.ToString());
if (data.Des == ID.NONE || MachineStuff.RemoveDeadMachines(data.Des))
{
// SwitchToMachine(MachineName.Trim());
MachineStuff.NewDesMachineID = DesMachineID = MachineID;
MachineStuff.SwitchLocation.X = Event.XY_BY_PIXEL + Event.myLastX;
MachineStuff.SwitchLocation.Y = Event.XY_BY_PIXEL + Event.myLastY;
MachineStuff.SwitchLocation.ResetCount();
EvSwitch.Set();
}
}
if (updateClientSockets)
{
MachineStuff.UpdateClientSockets("SkSend");
}
}
catch (Exception e)
{
Logger.Log(e);
}
#if DEBUG
startStop = DateTime.Now.Ticks - startStop;
totalSendTime += startStop;
if (startStop < minSendTime)
{
minSendTime = startStop;
}
if (startStop > maxSendTime)
{
maxSendTime = startStop;
}
avgSendTime = totalSendTime / totalSendCount;
#endif
}
else
{
Package.PackageSent.Nil++;
}
}