-
Notifications
You must be signed in to change notification settings - Fork 26
/
Copy pathApplicationWindow.cs
776 lines (653 loc) · 23.6 KB
/
ApplicationWindow.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
using ManagedShell.Common.Helpers;
using ManagedShell.Common.Logging;
using ManagedShell.Interop;
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Media;
using ManagedShell.Common.Enums;
namespace ManagedShell.WindowsTasks
{
[DebuggerDisplay("Title: {Title}, Handle: {Handle}")]
public class ApplicationWindow : IEquatable<ApplicationWindow>, INotifyPropertyChanged, IDisposable
{
const int TITLE_LENGTH = 1024;
private readonly TasksService _tasksService;
StringBuilder titleBuilder = new StringBuilder(TITLE_LENGTH);
public delegate void GetButtonRectEventHandler(ref NativeMethods.ShortRect rect);
public event GetButtonRectEventHandler GetButtonRect;
public ApplicationWindow(TasksService tasksService, IntPtr handle)
{
_tasksService = tasksService;
Handle = handle;
State = WindowState.Inactive;
}
public void Dispose()
{
// no longer required
}
public IntPtr Handle
{
get;
set;
}
private string _appUserModelId = null;
public string AppUserModelID
{
get
{
if (string.IsNullOrEmpty(_appUserModelId))
{
_appUserModelId = ShellHelper.GetAppUserModelIdPropertyForHandle(Handle);
}
return _appUserModelId;
}
}
private bool? _isUWP = null;
public bool IsUWP
{
get
{
if (_isUWP == null)
{
_isUWP = WinFileName.ToLower().Contains("applicationframehost.exe");
}
return (bool)_isUWP;
}
}
private string _winFileName = "";
public string WinFileName
{
get
{
if (string.IsNullOrEmpty(_winFileName))
{
_winFileName = ShellHelper.GetPathForWindowHandle(Handle);
}
return _winFileName;
}
}
private string _winFileDescription;
public string WinFileDescription
{
get
{
if (string.IsNullOrEmpty(_winFileDescription))
{
_winFileDescription = getFileDescription();
}
return _winFileDescription;
}
}
private uint? _procId;
public uint? ProcId => _procId = _procId ?? ShellHelper.GetProcIdForHandle(Handle);
private string _category;
public string Category
{
get
{
return _category;
}
set
{
if (value != _category)
{
_category = value;
OnPropertyChanged("Category");
}
}
}
private string _className;
public string ClassName
{
get
{
if (_className == null)
{
setClassName();
}
return _className;
}
}
private void setClassName()
{
string className = "";
try
{
StringBuilder cName = new StringBuilder(256);
NativeMethods.GetClassName(Handle, cName, cName.Capacity);
className = cName.ToString();
}
catch { }
if (_className != className)
{
_className = className;
OnPropertyChanged("ClassName");
}
}
private string _title;
public string Title
{
get
{
if (_title == null)
{
setTitle();
}
return _title;
}
}
private void setTitle()
{
string title = "";
try
{
titleBuilder.Clear();
NativeMethods.GetWindowText(Handle, titleBuilder, TITLE_LENGTH + 1);
title = titleBuilder.ToString();
}
catch { }
if (_title != title)
{
_title = title;
OnPropertyChanged("Title");
}
}
private bool _iconLoading;
private ImageSource _icon;
private IntPtr _hIcon = IntPtr.Zero;
public ImageSource Icon
{
get
{
if (_icon == null)
setIcon();
return _icon;
}
set
{
_icon = value;
OnPropertyChanged("Icon");
}
}
private ImageSource _overlayIcon;
public ImageSource OverlayIcon
{
get
{
return _overlayIcon;
}
private set
{
_overlayIcon = value;
OnPropertyChanged("OverlayIcon");
}
}
private string _overlayIconDescription;
public string OverlayIconDescription
{
get
{
return _overlayIconDescription;
}
private set
{
_overlayIconDescription = value;
OnPropertyChanged("OverlayIconDescription");
}
}
private NativeMethods.TBPFLAG _progressState;
public NativeMethods.TBPFLAG ProgressState
{
get
{
return _progressState;
}
set
{
_progressState = value;
if (value == NativeMethods.TBPFLAG.TBPF_NOPROGRESS)
{
ProgressValue = 0;
}
OnPropertyChanged("ProgressState");
}
}
private int _progressValue;
public int ProgressValue
{
get
{
return _progressValue;
}
set
{
_progressValue = value;
OnPropertyChanged("ProgressValue");
}
}
private WindowState _state;
public WindowState State
{
get
{
return _state;
}
set
{
_state = value;
OnPropertyChanged("State");
}
}
private IntPtr _hMonitor;
public IntPtr HMonitor
{
get
{
if (_hMonitor == IntPtr.Zero || EnvironmentHelper.IsWindows8OrBetter)
{
// Ignore the cache on Windows 8+, as it may be wrong.
SetMonitor();
}
return _hMonitor;
}
private set
{
if (_hMonitor != value)
{
if (_hMonitor != IntPtr.Zero)
{
ShellLogger.Debug($"ApplicationWindow: Monitor changed for {Handle} ({Title})");
}
_hMonitor = value;
OnPropertyChanged("HMonitor");
}
}
}
public bool IsMinimized
{
get { return NativeMethods.IsIconic(Handle); }
}
public NativeMethods.WindowShowStyle ShowStyle
{
get { return GetWindowShowStyle(Handle); }
}
public int WindowStyles
{
get
{
return NativeMethods.GetWindowLong(Handle, NativeMethods.GWL_STYLE);
}
}
public int ExtendedWindowStyles
{
get
{
return NativeMethods.GetWindowLong(Handle, NativeMethods.GWL_EXSTYLE);
}
}
public bool CanAddToTaskbar
{
get
{
int extendedWindowStyles = ExtendedWindowStyles;
bool isWindow = NativeMethods.IsWindow(Handle);
bool isVisible = NativeMethods.IsWindowVisible(Handle);
bool isToolWindow = (extendedWindowStyles & (int)NativeMethods.ExtendedWindowStyles.WS_EX_TOOLWINDOW) != 0;
bool isAppWindow = (extendedWindowStyles & (int)NativeMethods.ExtendedWindowStyles.WS_EX_APPWINDOW) != 0;
bool isNoActivate = (extendedWindowStyles & (int)NativeMethods.ExtendedWindowStyles.WS_EX_NOACTIVATE) != 0;
bool isDeleted = NativeMethods.GetProp(Handle, "ITaskList_Deleted") != IntPtr.Zero;
IntPtr ownerWin = NativeMethods.GetWindow(Handle, NativeMethods.GetWindow_Cmd.GW_OWNER);
return isWindow && isVisible && (ownerWin == IntPtr.Zero || isAppWindow) && (!isNoActivate || isAppWindow) && !isToolWindow && !isDeleted;
}
}
public bool CanMinimize => (WindowStyles & (int)NativeMethods.WindowStyles.WS_MINIMIZEBOX) != 0 && NativeMethods.IsWindowEnabled(Handle);
private bool? _showInTaskbar;
// True if this window should be shown in the taskbar
public bool ShowInTaskbar
{
get
{
if (_showInTaskbar == null)
{
SetShowInTaskbar();
}
return (bool)_showInTaskbar;
}
}
public void SetShowInTaskbar()
{
bool showInTaskbar = getShowInTaskbar();
if (_showInTaskbar != showInTaskbar)
{
_showInTaskbar = showInTaskbar;
// If we are becoming visible in the taskbar, get the category if it hasn't been set yet
if (_showInTaskbar == true && Category == null)
{
Category = _tasksService.TaskCategoryProvider?.GetCategory(this);
}
OnPropertyChanged("ShowInTaskbar");
}
}
private bool getShowInTaskbar()
{
// EnumWindows and ShellHook return UWP app windows that are 'cloaked', which should not be visible in the taskbar.
if (EnvironmentHelper.IsWindows8OrBetter)
{
int cbSize = Marshal.SizeOf(typeof(uint));
NativeMethods.DwmGetWindowAttribute(Handle, NativeMethods.DWMWINDOWATTRIBUTE.DWMWA_CLOAKED, out var cloaked, cbSize);
if (cloaked > 0)
{
ShellLogger.Debug($"ApplicationWindow: Cloaked window {Handle} ({Title}) hidden from taskbar");
return false;
}
// UWP shell windows that are not cloaked should be hidden from the taskbar, too.
if (IsImmersiveShellWindow())
{
ShellLogger.Debug($"ApplicationWindow: Hiding immersive shell window {Handle} ({Title}) from taskbar");
return false;
}
}
return CanAddToTaskbar;
}
public bool IsImmersiveShellWindow()
{
if (!EnvironmentHelper.IsWindows8OrBetter)
{
return false;
}
if (ClassName == "ApplicationFrameWindow" || ClassName == "Windows.UI.Core.CoreWindow" || ClassName == "StartMenuSizingFrame" || ClassName == "Shell_LightDismissOverlay")
{
if ((ExtendedWindowStyles & (int)NativeMethods.ExtendedWindowStyles.WS_EX_WINDOWEDGE) == 0)
{
return true;
}
}
else if (!EnvironmentHelper.IsWindows10OrBetter && (ClassName == "ImmersiveBackgroundWindow" || ClassName == "SearchPane" || ClassName == "NativeHWNDHost" || ClassName == "Shell_CharmWindow" || ClassName == "ImmersiveLauncher") && WinFileName.ToLower().Contains("explorer.exe"))
{
return true;
}
return false;
}
private string getFileDescription()
{
string desc;
try
{
desc = FileVersionInfo.GetVersionInfo(WinFileName).FileDescription;
}
catch (Exception e)
{
ShellLogger.Warning($"ApplicationWindow: Unable to get file description for {WinFileName} ({Title}): {e.Message}");
desc = Title;
}
return desc;
}
private void setIcon()
{
if (!_iconLoading && ShowInTaskbar)
{
_iconLoading = true;
Task.Factory.StartNew(() =>
{
if (IsUWP && !string.IsNullOrEmpty(AppUserModelID))
{
// UWP apps
try
{
var storeApp = UWPInterop.StoreAppHelper.AppList.GetAppByAumid(AppUserModelID);
if (storeApp != null)
{
Icon = storeApp.GetIconImageSource(_tasksService.TaskIconSize);
}
else
{
Icon = IconImageConverter.GetDefaultIcon();
}
}
catch
{
if (_icon == null) Icon = IconImageConverter.GetDefaultIcon();
}
}
else
{
// non-UWP apps
IntPtr hIco = default;
uint WM_GETICON = (uint)NativeMethods.WM.GETICON;
uint WM_QUERYDRAGICON = (uint)NativeMethods.WM.QUERYDRAGICON;
int GCL_HICON = -14;
int GCL_HICONSM = -34;
IconSize sizeSetting = _tasksService.TaskIconSize;
if (sizeSetting == IconSize.Small)
{
NativeMethods.SendMessageTimeout(Handle, WM_GETICON, 2, 0, 2, 1000, ref hIco);
if (hIco == IntPtr.Zero)
NativeMethods.SendMessageTimeout(Handle, WM_GETICON, 0, 0, 2, 1000, ref hIco);
}
else
{
NativeMethods.SendMessageTimeout(Handle, WM_GETICON, 1, 0, 2, 1000, ref hIco);
}
if (hIco == IntPtr.Zero && sizeSetting == IconSize.Small)
{
if (!Environment.Is64BitProcess)
hIco = NativeMethods.GetClassLong(Handle, GCL_HICONSM);
else
hIco = NativeMethods.GetClassLongPtr(Handle, GCL_HICONSM);
}
if (hIco == IntPtr.Zero)
{
if (!Environment.Is64BitProcess)
hIco = NativeMethods.GetClassLong(Handle, GCL_HICON);
else
hIco = NativeMethods.GetClassLongPtr(Handle, GCL_HICON);
}
if (hIco == IntPtr.Zero)
{
NativeMethods.SendMessageTimeout(Handle, WM_QUERYDRAGICON, 0, 0, 0, 1000, ref hIco);
}
if (hIco == IntPtr.Zero && _icon == null)
{
// last resort: find icon by executable. if we already have an icon from a previous fetch, then just skip this
if (ShellHelper.Exists(WinFileName))
{
IconSize size = IconSize.Small;
if (sizeSetting != size)
size = IconSize.Large;
hIco = IconHelper.GetIconByFilename(WinFileName, size);
}
}
if (hIco != IntPtr.Zero)
{
if (_hIcon != hIco)
{
_hIcon = hIco;
bool returnDefault = (_icon == null); // only return a default icon if we don't already have one. otherwise let's use what we have.
ImageSource icon = IconImageConverter.GetImageFromHIcon(hIco, returnDefault);
if (icon != null)
{
icon.Freeze();
Icon = icon;
}
}
else
{
NativeMethods.DestroyIcon(hIco);
}
}
}
_iconLoading = false;
}, CancellationToken.None, TaskCreationOptions.None, IconHelper.IconScheduler);
}
}
internal void SetMonitor()
{
HMonitor = NativeMethods.MonitorFromWindow(Handle, NativeMethods.MONITOR_DEFAULTTONEAREST);
}
internal NativeMethods.ShortRect GetButtonRectFromShell()
{
NativeMethods.ShortRect rect = new NativeMethods.ShortRect();
GetButtonRect?.Invoke(ref rect);
return rect;
}
public void SetOverlayIcon(IntPtr hIcon)
{
if (hIcon == IntPtr.Zero)
{
OverlayIcon = null;
return;
}
ImageSource icon = IconImageConverter.GetImageFromHIcon(hIcon, false);
if (icon != null)
{
icon.Freeze();
OverlayIcon = icon;
}
}
public void SetOverlayIconDescription(IntPtr lParam)
{
try
{
if (ProcId is uint procId)
{
if (lParam == IntPtr.Zero)
{
return;
}
IntPtr hShared = NativeMethods.SHLockShared(lParam, procId);
if (hShared == IntPtr.Zero)
{
return;
}
string str = Marshal.PtrToStringAuto(hShared);
NativeMethods.SHUnlockShared(hShared);
OverlayIconDescription = str;
}
}
catch (Exception e)
{
ShellLogger.Error($"ApplicationWindow: Unable to get overlay icon description from process {Title}: {e.Message}");
}
}
internal void UpdateProperties()
{
setTitle();
SetShowInTaskbar();
setIcon();
}
public void BringToFront()
{
// call restore if window is minimized
if (IsMinimized)
{
Restore();
}
else
{
// If the window is maximized, use ShowMaximize so that it doesn't un-maximize
if (GetWindowShowStyle(Handle) != NativeMethods.WindowShowStyle.ShowMaximized ||
!NativeMethods.ShowWindow(Handle, NativeMethods.WindowShowStyle.ShowMaximized))
{
NativeMethods.ShowWindow(Handle, NativeMethods.WindowShowStyle.Show);
}
makeForeground();
if (State == WindowState.Flashing) State = WindowState.Active; // some stubborn windows (Outlook) start flashing while already active, this lets us stop
}
}
public void Minimize()
{
if (!CanMinimize)
{
return;
}
NativeMethods.GetWindowThreadProcessId(Handle, out uint procId);
NativeMethods.AllowSetForegroundWindow(procId);
NativeMethods.PostMessage(Handle, (int)NativeMethods.WM.SYSCOMMAND, (IntPtr)NativeMethods.SC_MINIMIZE, IntPtr.Zero);
}
public void Restore()
{
IntPtr retval = IntPtr.Zero;
NativeMethods.SendMessageTimeout(Handle, (int)NativeMethods.WM.SYSCOMMAND, NativeMethods.SC_RESTORE, 0, 2, 200, ref retval);
makeForeground();
}
public void Maximize()
{
bool maximizeResult = NativeMethods.ShowWindow(Handle, NativeMethods.WindowShowStyle.Maximize);
if (!maximizeResult)
{
// we don't have a fallback for elevated windows here since our only hope, SC_MAXIMIZE, doesn't seem to work for them. fall back to restore.
IntPtr retval = IntPtr.Zero;
NativeMethods.SendMessageTimeout(Handle, (int)NativeMethods.WM.SYSCOMMAND, NativeMethods.SC_RESTORE, 0, 2, 200, ref retval);
}
makeForeground();
}
private void makeForeground()
{
NativeMethods.SetForegroundWindow(NativeMethods.GetLastActivePopup(Handle));
}
internal IntPtr DoClose()
{
makeForeground();
IntPtr retval = IntPtr.Zero;
NativeMethods.SendMessageTimeout(Handle, (int)NativeMethods.WM.SYSCOMMAND, NativeMethods.SC_CLOSE, 0, 2, 200, ref retval);
return retval;
}
public void Close()
{
_tasksService.CloseWindow(this);
}
public void Move()
{
// move window via arrow keys; must be active window to control
BringToFront();
IntPtr retval = IntPtr.Zero;
NativeMethods.SendMessageTimeout(Handle, (int)NativeMethods.WM.SYSCOMMAND, NativeMethods.SC_MOVE, 0, 2, 200, ref retval);
}
public void Size()
{
// size window via arrow keys; must be active window to control
BringToFront();
IntPtr retval = IntPtr.Zero;
NativeMethods.SendMessageTimeout(Handle, (int)NativeMethods.WM.SYSCOMMAND, NativeMethods.SC_SIZE, 0, 2, 200, ref retval);
}
/// <summary>
/// Returns whether a window is normal (1), minimized (2), or maximized (3).
/// </summary>
/// <param name="hWnd">The handle of the window.</param>
private NativeMethods.WindowShowStyle GetWindowShowStyle(IntPtr hWnd)
{
NativeMethods.WINDOWPLACEMENT placement = new NativeMethods.WINDOWPLACEMENT();
NativeMethods.GetWindowPlacement(hWnd, ref placement);
return placement.showCmd;
}
#region IEquatable<Window> Members
public bool Equals(ApplicationWindow other)
{
return Handle.Equals(other.Handle);
}
#endregion
#region INotifyPropertyChanged Members
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged(string PropertyName)
{
if (this.PropertyChanged != null)
{
this.PropertyChanged(this, new PropertyChangedEventArgs(PropertyName));
}
}
#endregion
public enum WindowState
{
Active,
Inactive,
Hidden,
Flashing,
Unknown = 999
}
}
}