-
Notifications
You must be signed in to change notification settings - Fork 61
/
VirtualDesktopServer2016.cs
2490 lines (2319 loc) · 97.5 KB
/
VirtualDesktopServer2016.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
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
// Author: Markus Scholtes, 2024
// Version 1.19, 2024-09-01
// Version for Windows 10 1607 to 1709 or Windows Server 2016
// Compile with:
// C:\Windows\Microsoft.NET\Framework\v4.0.30319\csc.exe VirtualDesktop1607.cs
using System;
using System.Runtime.InteropServices;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
// set attributes
using System.Reflection;
[assembly:AssemblyTitle("Command line tool to manage virtual desktops")]
[assembly:AssemblyDescription("Command line tool to manage virtual desktops")]
[assembly:AssemblyConfiguration("")]
[assembly:AssemblyCompany("MS")]
[assembly:AssemblyProduct("VirtualDesktop")]
[assembly:AssemblyCopyright("© Markus Scholtes 2024")]
[assembly:AssemblyTrademark("")]
[assembly:AssemblyCulture("")]
[assembly:AssemblyVersion("1.19.0.0")]
[assembly:AssemblyFileVersion("1.19.0.0")]
// Based on http://stackoverflow.com/a/32417530, Windows 10 SDK, github project Grabacr07/VirtualDesktop and own research
namespace VirtualDesktop
{
#region COM API
internal static class Guids
{
public static readonly Guid CLSID_ImmersiveShell = new Guid("C2F03A33-21F5-47FA-B4BB-156362A2F239");
public static readonly Guid CLSID_VirtualDesktopManagerInternal = new Guid("C5E0CDCA-7B6E-41B2-9FC4-D93975CC467B");
public static readonly Guid CLSID_VirtualDesktopManager = new Guid("AA509086-5CA9-4C25-8F95-589D3C07B48A");
public static readonly Guid CLSID_VirtualDesktopPinnedApps = new Guid("B5A399E7-1C87-46B8-88E9-FC5747B171BD");
}
[StructLayout(LayoutKind.Sequential)]
internal struct Size
{
public int X;
public int Y;
}
[StructLayout(LayoutKind.Sequential)]
internal struct Rect
{
public int Left;
public int Top;
public int Right;
public int Bottom;
}
internal enum APPLICATION_VIEW_CLOAK_TYPE : int
{
AVCT_NONE = 0,
AVCT_DEFAULT = 1,
AVCT_VIRTUAL_DESKTOP = 2
}
internal enum APPLICATION_VIEW_COMPATIBILITY_POLICY : int
{
AVCP_NONE = 0,
AVCP_SMALL_SCREEN = 1,
AVCP_TABLET_SMALL_SCREEN = 2,
AVCP_VERY_SMALL_SCREEN = 3,
AVCP_HIGH_SCALE_FACTOR = 4
}
[ComImport]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[Guid("9AC0B5C8-1484-4C5B-9533-4134A0F97CEA")]
internal interface IApplicationView
{
int SetFocus();
int SwitchTo();
int TryInvokeBack(IntPtr /* IAsyncCallback* */ callback);
int GetThumbnailWindow(out IntPtr hwnd);
int GetMonitor(out IntPtr /* IImmersiveMonitor */ immersiveMonitor);
int GetVisibility(out int visibility);
int SetCloak(APPLICATION_VIEW_CLOAK_TYPE cloakType, int unknown);
int GetPosition(ref Guid guid /* GUID for IApplicationViewPosition */, out IntPtr /* IApplicationViewPosition** */ position);
int SetPosition(ref IntPtr /* IApplicationViewPosition* */ position);
int InsertAfterWindow(IntPtr hwnd);
int GetExtendedFramePosition(out Rect rect);
int GetAppUserModelId([MarshalAs(UnmanagedType.LPWStr)] out string id);
int SetAppUserModelId(string id);
int IsEqualByAppUserModelId(string id, out int result);
int GetViewState(out uint state);
int SetViewState(uint state);
int GetNeediness(out int neediness);
int GetLastActivationTimestamp(out ulong timestamp);
int SetLastActivationTimestamp(ulong timestamp);
int GetVirtualDesktopId(out Guid guid);
int SetVirtualDesktopId(ref Guid guid);
int GetShowInSwitchers(out int flag);
int SetShowInSwitchers(int flag);
int GetScaleFactor(out int factor);
int CanReceiveInput(out bool canReceiveInput);
int GetCompatibilityPolicyType(out APPLICATION_VIEW_COMPATIBILITY_POLICY flags);
int SetCompatibilityPolicyType(APPLICATION_VIEW_COMPATIBILITY_POLICY flags);
int GetPositionPriority(out IntPtr /* IShellPositionerPriority** */ priority);
int SetPositionPriority(IntPtr /* IShellPositionerPriority* */ priority);
int GetSizeConstraints(IntPtr /* IImmersiveMonitor* */ monitor, out Size size1, out Size size2);
int GetSizeConstraintsForDpi(uint uint1, out Size size1, out Size size2);
int SetSizeConstraintsForDpi(ref uint uint1, ref Size size1, ref Size size2);
int QuerySizeConstraintsFromApp();
int OnMinSizePreferencesUpdated(IntPtr hwnd);
int ApplyOperation(IntPtr /* IApplicationViewOperation* */ operation);
int IsTray(out bool isTray);
int IsInHighZOrderBand(out bool isInHighZOrderBand);
int IsSplashScreenPresented(out bool isSplashScreenPresented);
int Flash();
int GetRootSwitchableOwner(out IApplicationView rootSwitchableOwner);
int EnumerateOwnershipTree(out IObjectArray ownershipTree);
int GetEnterpriseId([MarshalAs(UnmanagedType.LPWStr)] out string enterpriseId);
int IsMirrored(out bool isMirrored);
}
[ComImport]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[Guid("2C08ADF0-A386-4B35-9250-0FE183476FCC")]
internal interface IApplicationViewCollection
{
int GetViews(out IObjectArray array);
int GetViewsByZOrder(out IObjectArray array);
int GetViewsByAppUserModelId(string id, out IObjectArray array);
int GetViewForHwnd(IntPtr hwnd, out IApplicationView view);
int GetViewForApplication(object application, out IApplicationView view);
int GetViewForAppUserModelId(string id, out IApplicationView view);
int GetViewInFocus(out IntPtr view);
void RefreshCollection();
int RegisterForApplicationViewChanges(object listener, out int cookie);
int RegisterForApplicationViewPositionChanges(object listener, out int cookie);
int UnregisterForApplicationViewChanges(int cookie);
}
[ComImport]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[Guid("FF72FFDD-BE7E-43FC-9C03-AD81681E88E4")]
internal interface IVirtualDesktop
{
bool IsViewVisible(IApplicationView view);
Guid GetId();
}
[ComImport]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[Guid("F31574D6-B682-4CDC-BD56-1827860ABEC6")]
internal interface IVirtualDesktopManagerInternal
{
int GetCount();
void MoveViewToDesktop(IApplicationView view, IVirtualDesktop desktop);
bool CanViewMoveDesktops(IApplicationView view);
IVirtualDesktop GetCurrentDesktop();
void GetDesktops(out IObjectArray desktops);
[PreserveSig]
int GetAdjacentDesktop(IVirtualDesktop from, int direction, out IVirtualDesktop desktop);
void SwitchDesktop(IVirtualDesktop desktop);
IVirtualDesktop CreateDesktop();
void RemoveDesktop(IVirtualDesktop desktop, IVirtualDesktop fallback);
IVirtualDesktop FindDesktop(ref Guid desktopid);
}
[ComImport]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[Guid("A5CD92FF-29BE-454C-8D04-D82879FB3F1B")]
internal interface IVirtualDesktopManager
{
bool IsWindowOnCurrentVirtualDesktop(IntPtr topLevelWindow);
Guid GetWindowDesktopId(IntPtr topLevelWindow);
void MoveWindowToDesktop(IntPtr topLevelWindow, ref Guid desktopId);
}
[ComImport]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[Guid("4CE81583-1E4C-4632-A621-07A53543148F")]
internal interface IVirtualDesktopPinnedApps
{
bool IsAppIdPinned(string appId);
void PinAppID(string appId);
void UnpinAppID(string appId);
bool IsViewPinned(IApplicationView applicationView);
void PinView(IApplicationView applicationView);
void UnpinView(IApplicationView applicationView);
}
[ComImport]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[Guid("92CA9DCD-5622-4BBA-A805-5E9F541BD8C9")]
internal interface IObjectArray
{
void GetCount(out int count);
void GetAt(int index, ref Guid iid, [MarshalAs(UnmanagedType.Interface)]out object obj);
}
[ComImport]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[Guid("6D5140C1-7436-11CE-8034-00AA006009FA")]
internal interface IServiceProvider10
{
[return: MarshalAs(UnmanagedType.IUnknown)]
object QueryService(ref Guid service, ref Guid riid);
}
#endregion
#region COM wrapper
internal static class DesktopManager
{
static DesktopManager()
{
var shell = (IServiceProvider10)Activator.CreateInstance(Type.GetTypeFromCLSID(Guids.CLSID_ImmersiveShell));
VirtualDesktopManagerInternal = (IVirtualDesktopManagerInternal)shell.QueryService(Guids.CLSID_VirtualDesktopManagerInternal, typeof(IVirtualDesktopManagerInternal).GUID);
VirtualDesktopManager = (IVirtualDesktopManager)Activator.CreateInstance(Type.GetTypeFromCLSID(Guids.CLSID_VirtualDesktopManager));
ApplicationViewCollection = (IApplicationViewCollection)shell.QueryService(typeof(IApplicationViewCollection).GUID, typeof(IApplicationViewCollection).GUID);
VirtualDesktopPinnedApps = (IVirtualDesktopPinnedApps)shell.QueryService(Guids.CLSID_VirtualDesktopPinnedApps, typeof(IVirtualDesktopPinnedApps).GUID);
}
internal static IVirtualDesktopManagerInternal VirtualDesktopManagerInternal;
internal static IVirtualDesktopManager VirtualDesktopManager;
internal static IApplicationViewCollection ApplicationViewCollection;
internal static IVirtualDesktopPinnedApps VirtualDesktopPinnedApps;
internal static IVirtualDesktop GetDesktop(int index)
{ // get desktop with index
int count = VirtualDesktopManagerInternal.GetCount();
if (index < 0 || index >= count) throw new ArgumentOutOfRangeException("index");
IObjectArray desktops;
VirtualDesktopManagerInternal.GetDesktops(out desktops);
object objdesktop;
desktops.GetAt(index, typeof(IVirtualDesktop).GUID, out objdesktop);
Marshal.ReleaseComObject(desktops);
return (IVirtualDesktop)objdesktop;
}
internal static int GetDesktopIndex(IVirtualDesktop desktop)
{ // get index of desktop
int index = -1;
Guid IdSearch = desktop.GetId();
IObjectArray desktops;
VirtualDesktopManagerInternal.GetDesktops(out desktops);
object objdesktop;
for (int i = 0; i < VirtualDesktopManagerInternal.GetCount(); i++)
{
desktops.GetAt(i, typeof(IVirtualDesktop).GUID, out objdesktop);
if (IdSearch.CompareTo(((IVirtualDesktop)objdesktop).GetId()) == 0)
{ index = i;
break;
}
}
Marshal.ReleaseComObject(desktops);
return index;
}
internal static IApplicationView GetApplicationView(this IntPtr hWnd)
{ // get application view to window handle
IApplicationView view;
ApplicationViewCollection.GetViewForHwnd(hWnd, out view);
return view;
}
internal static string GetAppId(IntPtr hWnd)
{ // get Application ID to window handle
string appId;
hWnd.GetApplicationView().GetAppUserModelId(out appId);
return appId;
}
}
#endregion
#region public interface
public class Desktop
{
// get window handle to class and window name
[DllImport("User32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
// get process id to window handle
[DllImport("user32.dll")]
private static extern uint GetWindowThreadProcessId(IntPtr hWnd, out int lpdwProcessId);
// get thread id of current process
[DllImport("kernel32.dll")]
static extern uint GetCurrentThreadId();
// attach input to thread
[DllImport("user32.dll")]
static extern bool AttachThreadInput(uint idAttach, uint idAttachTo, bool fAttach);
// get handle of active window
[DllImport("user32.dll")]
private static extern IntPtr GetForegroundWindow();
// try to set foreground window
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]static extern bool SetForegroundWindow(IntPtr hWnd);
// send message to window
[DllImport("user32.dll")]
static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
private const int SW_MINIMIZE = 6;
private static readonly Guid AppOnAllDesktops = new Guid("BB64D5B7-4DE3-4AB2-A87C-DB7601AEA7DC");
private static readonly Guid WindowOnAllDesktops = new Guid("C2DDEA68-66F2-4CF9-8264-1BFD00FBBBAC");
private IVirtualDesktop ivd;
private Desktop(IVirtualDesktop desktop) { this.ivd = desktop; }
public override int GetHashCode()
{ // get hash
return ivd.GetHashCode();
}
public override bool Equals(object obj)
{ // compare with object
var desk = obj as Desktop;
return desk != null && object.ReferenceEquals(this.ivd, desk.ivd);
}
public static int Count
{ // return the number of desktops
get { return DesktopManager.VirtualDesktopManagerInternal.GetCount(); }
}
public static Desktop Current
{ // returns current desktop
get { return new Desktop(DesktopManager.VirtualDesktopManagerInternal.GetCurrentDesktop()); }
}
public static Desktop FromIndex(int index)
{ // return desktop object from index (-> index = 0..Count-1)
return new Desktop(DesktopManager.GetDesktop(index));
}
public static Desktop FromWindow(IntPtr hWnd)
{ // return desktop object to desktop on which window <hWnd> is displayed
if (hWnd == IntPtr.Zero) throw new ArgumentNullException();
Guid id = DesktopManager.VirtualDesktopManager.GetWindowDesktopId(hWnd);
if ((id.CompareTo(AppOnAllDesktops) == 0) || (id.CompareTo(WindowOnAllDesktops) == 0))
return new Desktop(DesktopManager.VirtualDesktopManagerInternal.GetCurrentDesktop());
else
return new Desktop(DesktopManager.VirtualDesktopManagerInternal.FindDesktop(ref id));
}
public static int FromDesktop(Desktop desktop)
{ // return index of desktop object or -1 if not found
return DesktopManager.GetDesktopIndex(desktop.ivd);
}
public static string DesktopNameFromDesktop(Desktop desktop)
{ // return name of desktop or "Desktop n" if it has no name
Guid guid = desktop.ivd.GetId();
// read desktop name in registry
string desktopName = null;
try {
desktopName = (string)Microsoft.Win32.Registry.GetValue("HKEY_CURRENT_USER\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Explorer\\VirtualDesktops\\Desktops\\{" + guid.ToString() + "}", "Name", null);
}
catch { }
// no name found, generate generic name
if (string.IsNullOrEmpty(desktopName))
{ // create name "Desktop n" (n = number starting with 1)
desktopName = "Desktop " + (DesktopManager.GetDesktopIndex(desktop.ivd) + 1).ToString();
}
return desktopName;
}
public static string DesktopNameFromIndex(int index)
{ // return name of desktop from index (-> index = 0..Count-1) or "Desktop n" if it has no name
Guid guid = DesktopManager.GetDesktop(index).GetId();
// read desktop name in registry
string desktopName = null;
try {
desktopName = (string)Microsoft.Win32.Registry.GetValue("HKEY_CURRENT_USER\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Explorer\\VirtualDesktops\\Desktops\\{" + guid.ToString() + "}", "Name", null);
}
catch { }
// no name found, generate generic name
if (string.IsNullOrEmpty(desktopName))
{ // create name "Desktop n" (n = number starting with 1)
desktopName = "Desktop " + (index + 1).ToString();
}
return desktopName;
}
public static int SearchDesktop(string partialName)
{ // get index of desktop with partial name, return -1 if no desktop found
int index = -1;
for (int i = 0; i < DesktopManager.VirtualDesktopManagerInternal.GetCount(); i++)
{ // loop through all virtual desktops and compare partial name to desktop name
if (DesktopNameFromIndex(i).ToUpper().IndexOf(partialName.ToUpper()) >= 0)
{ index = i;
break;
}
}
return index;
}
public static Desktop Create()
{ // create a new desktop
return new Desktop(DesktopManager.VirtualDesktopManagerInternal.CreateDesktop());
}
public void Remove(Desktop fallback = null)
{ // destroy desktop and switch to <fallback>
IVirtualDesktop fallbackdesktop;
if (fallback == null)
{ // if no fallback is given use desktop to the left except for desktop 0.
Desktop dtToCheck = new Desktop(DesktopManager.GetDesktop(0));
if (this.Equals(dtToCheck))
{ // desktop 0: set fallback to second desktop (= "right" desktop)
DesktopManager.VirtualDesktopManagerInternal.GetAdjacentDesktop(ivd, 4, out fallbackdesktop); // 4 = RightDirection
}
else
{ // set fallback to "left" desktop
DesktopManager.VirtualDesktopManagerInternal.GetAdjacentDesktop(ivd, 3, out fallbackdesktop); // 3 = LeftDirection
}
}
else
// set fallback desktop
fallbackdesktop = fallback.ivd;
DesktopManager.VirtualDesktopManagerInternal.RemoveDesktop(ivd, fallbackdesktop);
}
public static void RemoveAll()
{ // remove all desktops but visible
int desktopcount = DesktopManager.VirtualDesktopManagerInternal.GetCount();
int desktopcurrent = DesktopManager.GetDesktopIndex(DesktopManager.VirtualDesktopManagerInternal.GetCurrentDesktop());
if (desktopcurrent < desktopcount-1)
{ // remove all desktops "right" from current
for (int i = desktopcount-1; i > desktopcurrent; i--)
DesktopManager.VirtualDesktopManagerInternal.RemoveDesktop(DesktopManager.GetDesktop(i), DesktopManager.VirtualDesktopManagerInternal.GetCurrentDesktop());
}
if (desktopcurrent > 0)
{ // remove all desktops "left" from current
for (int i = 0; i < desktopcurrent; i++)
DesktopManager.VirtualDesktopManagerInternal.RemoveDesktop(DesktopManager.GetDesktop(0), DesktopManager.VirtualDesktopManagerInternal.GetCurrentDesktop());
}
}
public bool IsVisible
{ // return true if this desktop is the current displayed one
get { return object.ReferenceEquals(ivd, DesktopManager.VirtualDesktopManagerInternal.GetCurrentDesktop()); }
}
public void MakeVisible()
{ // make this desktop visible
IntPtr hWnd = FindWindow("Progman", "Program Manager");
// activate desktop to prevent flashing icons in taskbar
int dummy;
uint DesktopThreadId = GetWindowThreadProcessId(hWnd, out dummy);
uint ForegroundThreadId = GetWindowThreadProcessId(GetForegroundWindow(), out dummy);
uint CurrentThreadId = GetCurrentThreadId();
if ((DesktopThreadId != 0) && (ForegroundThreadId != 0) && (ForegroundThreadId != CurrentThreadId))
{
AttachThreadInput(DesktopThreadId, CurrentThreadId, true);
AttachThreadInput(ForegroundThreadId, CurrentThreadId, true);
SetForegroundWindow(hWnd);
AttachThreadInput(ForegroundThreadId, CurrentThreadId, false);
AttachThreadInput(DesktopThreadId, CurrentThreadId, false);
}
DesktopManager.VirtualDesktopManagerInternal.SwitchDesktop(ivd);
// direct desktop to give away focus
ShowWindow(hWnd, SW_MINIMIZE);
}
public Desktop Left
{ // return desktop at the left of this one, null if none
get
{
IVirtualDesktop desktop;
int hr = DesktopManager.VirtualDesktopManagerInternal.GetAdjacentDesktop(ivd, 3, out desktop); // 3 = LeftDirection
if (hr == 0)
return new Desktop(desktop);
else
return null;
}
}
public Desktop Right
{ // return desktop at the right of this one, null if none
get
{
IVirtualDesktop desktop;
int hr = DesktopManager.VirtualDesktopManagerInternal.GetAdjacentDesktop(ivd, 4, out desktop); // 4 = RightDirection
if (hr == 0)
return new Desktop(desktop);
else
return null;
}
}
public void MoveWindow(IntPtr hWnd)
{ // move window to this desktop
int processId;
if (hWnd == IntPtr.Zero) throw new ArgumentNullException();
GetWindowThreadProcessId(hWnd, out processId);
if (System.Diagnostics.Process.GetCurrentProcess().Id == processId)
{ // window of process
try // the easy way (if we are owner)
{
DesktopManager.VirtualDesktopManager.MoveWindowToDesktop(hWnd, ivd.GetId());
}
catch // window of process, but we are not the owner
{
IApplicationView view;
DesktopManager.ApplicationViewCollection.GetViewForHwnd(hWnd, out view);
DesktopManager.VirtualDesktopManagerInternal.MoveViewToDesktop(view, ivd);
}
}
else
{ // window of other process
IApplicationView view;
DesktopManager.ApplicationViewCollection.GetViewForHwnd(hWnd, out view);
try {
DesktopManager.VirtualDesktopManagerInternal.MoveViewToDesktop(view, ivd);
}
catch
{ // could not move active window, try main window (or whatever windows thinks is the main window)
DesktopManager.ApplicationViewCollection.GetViewForHwnd(System.Diagnostics.Process.GetProcessById(processId).MainWindowHandle, out view);
DesktopManager.VirtualDesktopManagerInternal.MoveViewToDesktop(view, ivd);
}
}
}
public void MoveActiveWindow()
{ // move active window to this desktop
MoveWindow(GetForegroundWindow());
}
public bool HasWindow(IntPtr hWnd)
{ // return true if window is on this desktop
if (hWnd == IntPtr.Zero) throw new ArgumentNullException();
Guid id = DesktopManager.VirtualDesktopManager.GetWindowDesktopId(hWnd);
if ((id.CompareTo(AppOnAllDesktops) == 0) || (id.CompareTo(WindowOnAllDesktops) == 0))
return true;
else
return ivd.GetId() == id;
}
public static bool IsWindowPinned(IntPtr hWnd)
{ // return true if window is pinned to all desktops
if (hWnd == IntPtr.Zero) throw new ArgumentNullException();
return DesktopManager.VirtualDesktopPinnedApps.IsViewPinned(hWnd.GetApplicationView());
}
public static void PinWindow(IntPtr hWnd)
{ // pin window to all desktops
if (hWnd == IntPtr.Zero) throw new ArgumentNullException();
var view = hWnd.GetApplicationView();
if (!DesktopManager.VirtualDesktopPinnedApps.IsViewPinned(view))
{ // pin only if not already pinned
DesktopManager.VirtualDesktopPinnedApps.PinView(view);
}
}
public static void UnpinWindow(IntPtr hWnd)
{ // unpin window from all desktops
if (hWnd == IntPtr.Zero) throw new ArgumentNullException();
var view = hWnd.GetApplicationView();
if (DesktopManager.VirtualDesktopPinnedApps.IsViewPinned(view))
{ // unpin only if not already unpinned
DesktopManager.VirtualDesktopPinnedApps.UnpinView(view);
}
}
public static bool IsApplicationPinned(IntPtr hWnd)
{ // return true if application for window is pinned to all desktops
if (hWnd == IntPtr.Zero) throw new ArgumentNullException();
return DesktopManager.VirtualDesktopPinnedApps.IsAppIdPinned(DesktopManager.GetAppId(hWnd));
}
public static void PinApplication(IntPtr hWnd)
{ // pin application for window to all desktops
if (hWnd == IntPtr.Zero) throw new ArgumentNullException();
string appId = DesktopManager.GetAppId(hWnd);
if (!DesktopManager.VirtualDesktopPinnedApps.IsAppIdPinned(appId))
{ // pin only if not already pinned
DesktopManager.VirtualDesktopPinnedApps.PinAppID(appId);
}
}
public static void UnpinApplication(IntPtr hWnd)
{ // unpin application for window from all desktops
if (hWnd == IntPtr.Zero) throw new ArgumentNullException();
var view = hWnd.GetApplicationView();
string appId = DesktopManager.GetAppId(hWnd);
if (DesktopManager.VirtualDesktopPinnedApps.IsAppIdPinned(appId))
{ // unpin only if pinned
DesktopManager.VirtualDesktopPinnedApps.UnpinAppID(appId);
}
}
}
#endregion
}
namespace VDeskTool
{
static class Program
{
static bool verbose = true;
static bool breakonerror = true;
static bool wrapdesktops = false;
static int rc = 0;
static int Main(string[] args)
{
if (args.Length == 0)
{ // no arguments, show help screen
HelpScreen();
return -2;
}
foreach (string arg in args)
{
System.Text.RegularExpressions.GroupCollection groups = System.Text.RegularExpressions.Regex.Match(arg, @"^[-\/]?([^:=]+)[:=]?(.*)$").Groups;
if (groups.Count != 3)
{ // parameter error
rc = -2;
}
else
{ // reset return code if on error
if (rc < 0) rc = 0;
if (groups[2].Value == "")
{ // parameter without value
switch(groups[1].Value.ToUpper())
{
case "HELP": // help screen
case "H":
case "?":
HelpScreen();
return 0;
case "QUIET": // don't display messages
case "Q":
verbose = false;
break;
case "VERBOSE": // display messages
case "V":
Console.WriteLine("Verbose mode enabled");
verbose = true;
break;
case "BREAK": // break on error
case "B":
if (verbose) Console.WriteLine("Break on error enabled");
breakonerror = true;
break;
case "CONTINUE": // continue on error
case "CO":
if (verbose) Console.WriteLine("Break on error disabled");
breakonerror = false;
break;
case "WRAP": // wrap desktops using "LEFT" or "RIGHT"
case "W":
if (verbose) Console.WriteLine("Wrapping desktops enabled");
wrapdesktops = true;
break;
case "NOWRAP": // do not wrap desktops
case "NW":
if (verbose) Console.WriteLine("Wrapping desktop disabled");
wrapdesktops = false;
break;
case "COUNT": // get count of desktops
case "C":
rc = VirtualDesktop.Desktop.Count;
if (verbose) Console.WriteLine("Count of desktops: " + rc);
break;
case "LIST": // show list of desktops
case "LI":
int desktopCount = VirtualDesktop.Desktop.Count;
int visibleDesktop = VirtualDesktop.Desktop.FromDesktop(VirtualDesktop.Desktop.Current);
if (verbose)
{
Console.WriteLine("Virtual desktops:");
Console.WriteLine("-----------------");
}
for (int i = 0; i < desktopCount; i++)
{
if (i != visibleDesktop)
Console.WriteLine(VirtualDesktop.Desktop.DesktopNameFromIndex(i));
else
Console.WriteLine(VirtualDesktop.Desktop.DesktopNameFromIndex(i) + " (visible)");
}
if (verbose) Console.WriteLine("\nCount of desktops: " + desktopCount);
break;
case "GETCURRENTDESKTOP": // get number of current desktop and display desktop name
case "GCD":
rc = VirtualDesktop.Desktop.FromDesktop(VirtualDesktop.Desktop.Current);
if (verbose) Console.WriteLine("Current desktop: '" + VirtualDesktop.Desktop.DesktopNameFromDesktop(VirtualDesktop.Desktop.Current) + "' (desktop number " + rc + ")");
break;
case "ISVISIBLE": // is desktop in rc visible?
case "IV":
if ((rc >= 0) && (rc < VirtualDesktop.Desktop.Count))
{ // check if parameter is in range of active desktops
if (VirtualDesktop.Desktop.FromIndex(rc).IsVisible)
{
if (verbose) Console.WriteLine("Virtual desktop '" + VirtualDesktop.Desktop.DesktopNameFromIndex(rc) + "' (desktop number " + rc.ToString() + ") is visible");
rc = 0;
}
else
{
if (verbose) Console.WriteLine("Virtual desktop '" + VirtualDesktop.Desktop.DesktopNameFromIndex(rc) + "' (desktop number " + rc.ToString() + ") is not visible");
rc = 1;
}
}
else
rc = -1;
break;
case "SWITCH": // switch to desktop in rc
case "S":
if (verbose) Console.Write("Switching to virtual desktop number " + rc.ToString());
try
{ // activate virtual desktop rc
VirtualDesktop.Desktop.FromIndex(rc).MakeVisible();
if (verbose) Console.WriteLine(", desktop '" + VirtualDesktop.Desktop.DesktopNameFromIndex(rc) + "' is active now");
}
catch
{ // error while activating
if (verbose) Console.WriteLine();
rc = -1;
}
break;
case "LEFT": // switch to desktop to the left
case "L":
if (verbose) Console.Write("Switching to left virtual desktop");
try
{ // activate virtual desktop to the left
if (wrapdesktops && (VirtualDesktop.Desktop.FromDesktop(VirtualDesktop.Desktop.Current) == 0))
VirtualDesktop.Desktop.FromIndex(VirtualDesktop.Desktop.Count - 1).MakeVisible();
else
VirtualDesktop.Desktop.Current.Left.MakeVisible();
rc = VirtualDesktop.Desktop.FromDesktop(VirtualDesktop.Desktop.Current);
if (verbose) Console.WriteLine(", desktop number " + rc.ToString() + " ('" + VirtualDesktop.Desktop.DesktopNameFromIndex(rc) + "') is active now");
}
catch
{ // error while activating
if (verbose) Console.WriteLine();
rc = -1;
}
break;
case "RIGHT": // switch to desktop to the right
case "RI":
if (verbose) Console.Write("Switching to right virtual desktop");
try
{ // activate virtual desktop to the right
if (wrapdesktops && (VirtualDesktop.Desktop.FromDesktop(VirtualDesktop.Desktop.Current) == VirtualDesktop.Desktop.Count - 1))
VirtualDesktop.Desktop.FromIndex(0).MakeVisible();
else
VirtualDesktop.Desktop.Current.Right.MakeVisible();
rc = VirtualDesktop.Desktop.FromDesktop(VirtualDesktop.Desktop.Current);
if (verbose) Console.WriteLine(", desktop number " + rc.ToString() + " ('" + VirtualDesktop.Desktop.DesktopNameFromIndex(rc) + "') is active now");
}
catch
{ // error while activating
if (verbose) Console.WriteLine();
rc = -1;
}
break;
case "NEW": // create new desktop
case "N":
if (verbose) Console.Write("Creating virtual desktop");
try
{ // create virtual desktop, number is stored in rc
rc = VirtualDesktop.Desktop.FromDesktop(VirtualDesktop.Desktop.Create());
if (verbose) Console.WriteLine(" number " + rc.ToString());
}
catch
{ // error while creating
Console.WriteLine();
rc = -1;
}
break;
case "REMOVE": // remove desktop in rc
case "R":
if (verbose)
{
Console.Write("Removing virtual desktop number " + rc.ToString());
if ((rc >= 0) && (rc < VirtualDesktop.Desktop.Count)) Console.WriteLine(" (desktop '" + VirtualDesktop.Desktop.DesktopNameFromIndex(rc) + "')");
}
try
{ // remove virtual desktop rc
VirtualDesktop.Desktop.FromIndex(rc).Remove();
}
catch
{ // error while removing
Console.WriteLine();
rc = -1;
}
break;
case "REMOVEALL": // remove all virtual desktops but visible
case "RA":
if (verbose) Console.WriteLine("Removing all virtual desktops but visible");
try
{ // remove all virtual desktops but visible
VirtualDesktop.Desktop.RemoveAll();
}
catch
{ // error while removing
rc = -1;
}
break;
case "MOVEACTIVEWINDOW": // move active window to desktop in rc
case "MAW":
if (verbose) Console.WriteLine("Moving active window to virtual desktop number " + rc.ToString());
try
{ // move active window
VirtualDesktop.Desktop.FromIndex(rc).MoveActiveWindow();
if (verbose) Console.WriteLine("Active window moved to desktop number " + rc.ToString() + " (desktop '" + VirtualDesktop.Desktop.DesktopNameFromIndex(rc) + "')");
}
catch
{ // error while moving
if (verbose) Console.WriteLine("No active window or move failed");
rc = -1;
}
break;
case "LISTWINDOWSONDESKTOP": // list window handles of windows shown on desktop in rc
case "LWOD":
if (verbose)
{
Console.Write("Listing handles of windows on virtual desktop number " + rc.ToString());
if ((rc >= 0) && (rc < VirtualDesktop.Desktop.Count)) Console.WriteLine(" (desktop '" + VirtualDesktop.Desktop.DesktopNameFromIndex(rc) + "')");
}
try
{ // list window handles on desktop rc
ListWindowsOnDesktop(rc);
}
catch
{ // error while listing
Console.WriteLine();
rc = -1;
}
break;
case "CLOSEWINDOWSONDESKTOP": // close windows shown on desktop in rc
case "CWOD":
if (verbose)
{
Console.Write("Closing windows on virtual desktop number " + rc.ToString());
if ((rc >= 0) && (rc < VirtualDesktop.Desktop.Count)) Console.WriteLine(" (desktop '" + VirtualDesktop.Desktop.DesktopNameFromIndex(rc) + "')");
}
try
{ // close windows on desktop rc
CloseWindowsOnDesktop(rc);
}
catch
{ // error while closing
Console.WriteLine();
rc = -1;
}
break;
case "WAITKEY": // wait for keypress
case "WK":
if (verbose) Console.WriteLine("Press a key");
Console.ReadKey(true);
break;
default:
rc = -2;
break;
}
}
else
{ // parameter with value
int iParam;
switch(groups[1].Value.ToUpper())
{
case "GETDESKTOP": // get desktop number
case "GD":
if (int.TryParse(groups[2].Value, out iParam))
{ // parameter is an integer, use as desktop number
if ((iParam >= 0) && (iParam < VirtualDesktop.Desktop.Count))
{ // check if parameter is in range of active desktops
if (verbose) Console.WriteLine("Virtual desktop number " + iParam.ToString() + " (desktop '" + VirtualDesktop.Desktop.DesktopNameFromIndex(iParam) + "') selected");
rc = iParam;
}
else
rc = -1;
}
else
{ // parameter is a string, search as part of desktop name
iParam = VirtualDesktop.Desktop.SearchDesktop(groups[2].Value);
if (iParam >= 0)
{ // desktop found
if (verbose) Console.WriteLine("Virtual desktop number " + iParam.ToString() + " (desktop '" + VirtualDesktop.Desktop.DesktopNameFromIndex(iParam) + "') selected");
rc = iParam;
}
else
{ // no desktop found
if ((groups[2].Value.ToUpper() == "LAST") || (groups[2].Value.ToUpper() == "*LAST*"))
{ // last desktop
iParam = VirtualDesktop.Desktop.Count-1;
if (verbose) Console.WriteLine("Virtual desktop number " + iParam.ToString() + " (desktop '" + VirtualDesktop.Desktop.DesktopNameFromIndex(iParam) + "') selected");
rc = iParam;
}
else
{ // no desktop found
if (verbose) Console.WriteLine("Could not find virtual desktop with name containing '" + groups[2].Value + "'");
rc = -2;
}
}
}
break;
case "ISVISIBLE": // is desktop visible?
case "IV":
if (int.TryParse(groups[2].Value, out iParam))
{ // parameter is an integer, use as desktop number
if ((iParam >= 0) && (iParam < VirtualDesktop.Desktop.Count))
{ // check if parameter is in range of active desktops
if (VirtualDesktop.Desktop.FromIndex(iParam).IsVisible)
{
if (verbose) Console.WriteLine("Virtual desktop number " + iParam.ToString() + " (desktop '" + VirtualDesktop.Desktop.DesktopNameFromIndex(iParam) + "') is visible");
rc = 0;
}
else
{
if (verbose) Console.WriteLine("Virtual desktop number " + iParam.ToString() + " (desktop '" + VirtualDesktop.Desktop.DesktopNameFromIndex(iParam) + "') is not visible");
rc = 1;
}
}
else
rc = -1;
}
else
{ // parameter is a string, search as part of desktop name
iParam = VirtualDesktop.Desktop.SearchDesktop(groups[2].Value);
if (iParam >= 0)
{ // desktop found
if (VirtualDesktop.Desktop.FromIndex(iParam).IsVisible)
{
if (verbose) Console.WriteLine("Virtual desktop number " + iParam.ToString() + " (desktop '" + VirtualDesktop.Desktop.DesktopNameFromIndex(iParam) + "') is visible");
rc = 0;
}
else
{
if (verbose) Console.WriteLine("Virtual desktop number " + iParam.ToString() + " (desktop '" + VirtualDesktop.Desktop.DesktopNameFromIndex(iParam) + "') is not visible");
rc = 1;
}
}
else
{ // no desktop found
if ((groups[2].Value.ToUpper() == "LAST") || (groups[2].Value.ToUpper() == "*LAST*"))
{ // last desktop
iParam = VirtualDesktop.Desktop.Count-1;
if (VirtualDesktop.Desktop.FromIndex(iParam).IsVisible)
{
if (verbose) Console.WriteLine("Virtual desktop number " + iParam.ToString() + " (desktop '" + VirtualDesktop.Desktop.DesktopNameFromIndex(iParam) + "') is visible");
rc = 0;
}
else
{
if (verbose) Console.WriteLine("Virtual desktop number " + iParam.ToString() + " (desktop '" + VirtualDesktop.Desktop.DesktopNameFromIndex(iParam) + "') is not visible");
rc = 1;
}
}
else
{ // no desktop found
if (verbose) Console.WriteLine("Could not find virtual desktop with name containing '" + groups[2].Value + "'");
rc = -2;
}
}
}
break;
case "SWITCH": // switch to desktop
case "S":