-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathMainPage.xaml.cs
1128 lines (1064 loc) · 44.3 KB
/
MainPage.xaml.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
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Threading.Tasks;
using System.Windows.Input;
using Microsoft.UI.Xaml;
using Microsoft.UI.Xaml.Controls;
using Microsoft.UI.Xaml.Input;
using Microsoft.UI.Xaml.Media;
using Windows.Storage.Streams;
using Windows.Graphics.Imaging;
using IconExtractor.Models;
using IconExtractor.Support;
using IconExtractor.Controls;
using TargetFrameworkAttribute = System.Runtime.Versioning.TargetFrameworkAttribute;
using InformationalAttribute = System.Reflection.AssemblyInformationalVersionAttribute;
using ConfigurationAttribute = System.Reflection.AssemblyConfigurationAttribute;
using FileVersionAttribute = System.Reflection.AssemblyFileVersionAttribute;
using ProductAttribute = System.Reflection.AssemblyProductAttribute;
using CompanyAttribute = System.Reflection.AssemblyCompanyAttribute;
using Microsoft.UI.Xaml.Media.Imaging;
using Windows.Foundation;
using Windows.ApplicationModel;
using System.Threading;
namespace IconExtractor;
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class MainPage : Page, INotifyPropertyChanged
{
#region [Props]
bool _loaded = false;
CancellationTokenSource _cts { get; set; } = new();
public event PropertyChangedEventHandler? PropertyChanged;
public ObservableCollection<IconIndexItem> IconItems { get; set; } = new();
public List<string> dlls = new List<string>
{
"aclui.dll",
"accessibilitycpl.dll",
"ActionCenter.dll",
"ActionCenterCPL.dll",
"AdmTmpl.dll",
"appmgr.dll",
"audiosrv.dll",
"AuditNativeSnapIn.dll",
"AuthFWGP.dll",
"autoplay.dll",
"basecsp.dll",
"azroleui.dll",
"bootux.dll",
"bthci.dll",
"btpanui.dll",
"BthpanContextHandler.dll",
"cabview.dll",
"CastingShellExt.dll",
"CertEnrollUI.dll",
"cewmdm.dll",
"certmgr.dll",
"cmdial32.dll",
"cmlua.dll",
"cmstplua.dll",
"colorui.dll",
"comres.dll",
"console.dll",
"ContentDeliveryManager.Utilities.dll",
"cryptuiwizard.dll",
"DAMM.dll",
"deskadp.dll",
"deskmon.dll",
"DeviceCenter.dll",
"DevicePairingFolder.dll",
"dfshim.dll",
"devmgr.dll",
"diagperf.dll",
"DiagCpl.dll",
"Display.dll",
"dmdskres.dll",
"dot3gpui.dll",
"dot3mm.dll",
"dskquoui.dll",
"dsprop.dll",
"dsquery.dll",
"DXP.dll",
"DxpTaskSync.dll",
"eapsimextdesktop.dll",
"EditionUpgradeManagerObj.dll",
"EhStorShell.dll",
"EhStorPwdMgr.dll",
"els.dll",
"ExplorerFrame.dll",
"fde.dll",
"fdprint.dll",
"fhcpl.dll",
"filemgmt.dll",
"FirewallControlPanel.dll",
"fontext.dll",
"fveui.dll",
"fvewiz.dll",
"fvecpl.dll",
"FXSCOMPOSERES.dll",
"gcdef.dll",
"gpprefcl.dll",
"gpedit.dll",
"hgcpl.dll",
"hnetcfg.dll",
"hotplug.dll",
"icm32.dll",
"icsigd.dll",
"iernonce.dll",
"ieframe.dll",
"imagesp1.dll",
"imageres.dll",
"input.dll",
"INETRES.dll",
"ipsecsnp.dll",
"ipsmsnap.dll",
"itss.dll",
"iscsicpl.dll",
"keymgr.dll",
"localsec.dll",
"mapi32.dll",
"mapistub.dll",
"mciavi32.dll",
"mferror.dll",
"miguiresource.dll",
"mmcshext.dll",
"mmcbase.dll",
"moricons.dll",
"mqsnap.dll",
"mqutil.dll",
"msacm32.dll",
"msctf.dll",
"mscandui.dll",
"msctfui.dll",
"msi.dll",
"msident.dll",
"msidntld.dll",
"msihnd.dll",
"msieftp.dll",
"msports.dll",
"mssvp.dll",
"mstsc.exe",
"msutb.dll",
"mstask.dll",
"msxml3.dll",
"mycomput.dll",
"mydocs.dll",
"ncpa.cpl",
"ndfapi.dll",
"netplwiz.dll",
"netcenter.dll",
"netshell.dll",
"networkexplorer.dll",
"newdev.dll",
"ntlanui2.dll",
"ntshrui.dll",
"nvcuda.dll",
"ole32.dll",
"objsel.dll",
"occache.dll",
"oleprn.dll",
"packager.dll",
"pifmgr.dll",
"photowiz.dll",
"pmcsnap.dll",
"pnpclean.dll",
"PortableDeviceStatus.dll",
"ppcsnap.dll",
"powercpl.dll",
"printui.dll",
"prnntfy.dll",
"prnfldr.dll",
"quartz.dll",
"RADCUI.dll",
"rasgcw.dll",
"RASMM.dll",
"rasdlg.dll",
"rdbui.dll",
"rastlsext.dll",
"rastls.dll",
"remotepg.dll",
"sberes.dll",
"scavengeui.dll",
"SCardDlg.dll",
"scksp.dll",
"scrobj.dll",
"sdhcinst.dll",
"scrptadm.dll",
"SearchFolder.dll",
"sdcpl.dll",
"SecurityHealthAgent.dll",
"SecurityHealthSSO.dll",
"setupapi.dll",
"SensorsCpl.dll",
"shlwapi.dll",
"shell32.dll",
"setupcln.dll",
"shwebsvc.dll",
"softkbd.dll",
"SndVolSSO.dll",
"SpaceControl.dll",
"sppcommdlg.dll",
"sppcomapi.dll",
"srm.dll",
"srchadmin.dll",
"srrstr.dll",
"SrpUxNativeSnapIn.dll",
"sti.dll",
"stobject.dll",
"sud.dll",
"sysclass.dll",
"SysFxUI.dll",
"Tabbtn.dll",
"tcpipcfg.dll",
"taskbarcpl.dll",
"tapiui.dll",
"themecpl.dll",
"tpmcompc.dll",
"TSWorkspace.dll",
"twext.dll",
"UIRibbonRes.dll",
"urlmon.dll",
"user32.dll",
"url.dll",
"usbui.dll",
"UserAccountControlSettings.dll",
"usercpl.dll",
"VAN.dll",
"Vault.dll",
"vfwwdm32.dll",
"wdc.dll",
"webcheck.dll",
"werui.dll",
"werconcpl.dll",
"wiaaut.dll",
"WFSR.dll",
"wiadefui.dll",
"wiashext.dll",
"Windows.Storage.Search.dll",
"Windows.UI.CredDialogController.dll",
"winmm.dll",
"wininetlui.dll",
"winsrv.dll",
"wlanpref.dll",
"wlangpui.dll",
"WMPhoto.dll",
"WorkfoldersControl.dll",
"wmploc.DLL",
"WorkFoldersRes.dll",
"wsecedit.dll",
"zipfldr.dll",
#region [Original Reference List]
//"imageres.dll",
//"shell32.dll",
//"ddores.dll",
//"wmploc.dll",
//"pifmgr.dll",
//"accessibilitycpl.dll",
//"moricons.dll",
//"mmcndmgr.dll",
//"mmres.dll",
//"netcenter.dll",
//"netshell.dll",
//"networkexplorer.dll",
//"pnidui.dll",
//"sensorscpl.dll",
//"setupapi.dll",
//"wpdshext.dll",
//"compstui.dll",
//"ieframe.dll",
//"dmdskres.dll",
//"dsuiext.dll",
//"mstscax.dll",
//"wiashext.dll",
//"comres.dll",
//"actioncentercpl.dll",
//"aclui.dll",
//"autoplay.dll",
//"comctl32.dll",
//"filemgmt.dll",
//"ncpa.cpl",
//"url.dll",
//"xwizards.dll",
//"imagesp1.dll",
//"mstsc.exe",
//"explorer.exe",
#endregion
};
private string _target = "imageres.dll";
public string TargetDLL
{
get => _target;
set
{
_target = value;
NotifyPropertyChanged(nameof(TargetDLL));
}
}
int _selectedDLLIndex = 0;
public int SelectedDLLIndex
{
get => _selectedDLLIndex;
set
{
_selectedDLLIndex = value;
NotifyPropertyChanged(nameof(SelectedDLLIndex));
}
}
private string _targetWidth = "32";
public string TargetWidth
{
get => _targetWidth;
set
{
_targetWidth = value;
NotifyPropertyChanged(nameof(TargetWidth));
}
}
private string _targetHeight = "32";
public string TargetHeight
{
get => _targetHeight;
set
{
_targetHeight = value;
NotifyPropertyChanged(nameof(TargetHeight));
}
}
private string _status = "";
public string Status
{
get => _status;
set
{
_status = value;
NotifyPropertyChanged(nameof(Status));
}
}
private bool _saveToDisk = false;
public bool SaveToDisk
{
get => _saveToDisk;
set
{
_saveToDisk = value;
NotifyPropertyChanged(nameof(SaveToDisk));
}
}
private bool _isBusy = false;
public bool IsBusy
{
get => _isBusy;
set
{
_isBusy = value;
NotifyPropertyChanged(nameof(IsBusy));
_isNotBusy = !_isBusy;
NotifyPropertyChanged(nameof(IsNotBusy));
}
}
private bool _isNotBusy = true;
public bool IsNotBusy
{
get => _isNotBusy;
set
{
_isNotBusy = value;
NotifyPropertyChanged(nameof(IsNotBusy));
_isBusy = !_isNotBusy;
NotifyPropertyChanged(nameof(IsBusy));
}
}
Microsoft.UI.Xaml.Media.ImageSource? _imgSource;
public ImageSource? ImgSource
{
get => _imgSource;
set
{
_imgSource = value;
NotifyPropertyChanged(nameof(ImgSource));
}
}
IconFileInfo? _ShieldIconFileInfo;
public IconFileInfo? ShieldIconFileInfo
{
get
{
if (_ShieldIconFileInfo is null)
{
var imageResList = Extensions.ExtractSelectedIconsFromDLL(
imageresPath,
new List<int>() { Constants.ImageRes.ShieldIcon },
24);
_ShieldIconFileInfo = imageResList.First();
}
return _ShieldIconFileInfo;
}
set
{
_ShieldIconFileInfo = value;
NotifyPropertyChanged(nameof(ShieldIconFileInfo));
}
}
IconFileInfo? _LandscapeIconFileInfo;
public IconFileInfo? LandscapeIconFileInfo
{
get
{
if (_LandscapeIconFileInfo is null)
{
var imageResList = Extensions.ExtractSelectedIconsFromDLL(
imageresPath,
new List<int>() { Constants.ImageRes.Desktop },
24);
_LandscapeIconFileInfo = imageResList.First();
}
return _LandscapeIconFileInfo;
}
set
{
_LandscapeIconFileInfo = value;
NotifyPropertyChanged(nameof(LandscapeIconFileInfo));
}
}
IconFileInfo? _MonitorIconFileInfo;
public IconFileInfo? MonitorIconFileInfo
{
get
{
if (_MonitorIconFileInfo is null)
{
var imageResList = Extensions.ExtractSelectedIconsFromDLL(
imageresPath,
new List<int>() { Constants.ImageRes.CPUMonitor },
24);
_MonitorIconFileInfo = imageResList.First();
}
return _MonitorIconFileInfo;
}
set
{
_MonitorIconFileInfo = value;
NotifyPropertyChanged(nameof(MonitorIconFileInfo));
}
}
IconFileInfo? _SearchIconFileInfo;
public IconFileInfo? SearchIconFileInfo
{
get
{
if (_SearchIconFileInfo is null)
{
var imageResList = Extensions.ExtractSelectedIconsFromDLL(
imageresPath,
new List<int>() { Constants.ImageRes.Search },
24);
_SearchIconFileInfo = imageResList.First();
}
return _SearchIconFileInfo;
}
set
{
_SearchIconFileInfo = value;
NotifyPropertyChanged(nameof(SearchIconFileInfo));
}
}
public string imageresPath { get; private set; } = System.IO.Path.Combine(Constants.UserEnvironmentPaths.SystemRootPath, "System32", "imageres.dll");
public string shell32Path { get; private set; } = System.IO.Path.Combine(Constants.UserEnvironmentPaths.SystemRootPath, "System32", "shell32.dll");
protected void NotifyPropertyChanged([CallerMemberName] string propertyName = "")
{
if (string.IsNullOrEmpty(propertyName))
return;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
public IconIndexItem SelectedIcon
{
get { return (IconIndexItem)GetValue(SelectedIconProperty); }
set { SetValue(SelectedIconProperty, value); }
}
public static readonly DependencyProperty SelectedIconProperty = DependencyProperty.Register(
nameof(SelectedIcon),
typeof(IconIndexItem),
typeof(MainPage),
new PropertyMetadata(null));
#endregion
public ICommand TraverseCommand { get; }
public ICommand TestCommand { get; }
public ICommand AboutCommand { get; }
public ICommand DebugCommand { get; }
public MainPage()
{
this.InitializeComponent();
IconsRepeater.Loaded += ItemsGridViewOnLoaded;
TraverseCommand = new RelayCommand<object>(async (obj) =>
{
//testPath = @"C:\Windows\SystemResources\shell32.dll.mun";
var testPath = System.IO.Path.Combine(Constants.UserEnvironmentPaths.SystemRootPath, "System32", TargetDLL);
if (!File.Exists(testPath))
{
Status = $"⚠️ DLL was not found";
return;
}
StoryboardPath.Resume();
IsBusy = true;
IconItems.Clear();
var request = Enumerable.Range(1, 3000).ToList();
Status = $"🔔 Checking {request.Count} indices…";
IList<IconFileInfo>? fullImageResList = null;
var extraction = Task.Run(() =>
{
fullImageResList = Extensions.ExtractSelectedIconsFromDLL(testPath, request, 64);
}).GetAwaiter();
extraction.OnCompleted(() =>
{
if (fullImageResList != null)
{
try
{
if (fullImageResList.Any())
{
int count = 0;
foreach (var img in fullImageResList)
{
if (!App.IsClosing && img is not null)
{
count++;
imgCycle?.DispatcherQueue.TryEnqueue(async () =>
{
var bmp = await img.IconData.ToBitmapAsync();
if (bmp is not null)
{
ImgSource = (Microsoft.UI.Xaml.Media.ImageSource)bmp;
//await TestBitmapCropper(ImgSource);
Status = $"Found index #{img.Index}";
IconItems.Add(new IconIndexItem { IconIndex = img.Index, IconImage = ImgSource });
if (SaveToDisk)
{
try
{ // NOTE: When extracting icon assets from a DLL, the UriSource does not exist.
// In an effort to make this feature a reality, I've created an "alternative" approach.
if (int.TryParse(TargetWidth, out int tw) && tw > 0 && int.TryParse(TargetHeight, out int th) && th > 0)
await BitmapHelper.SaveImageSourceToFileAsync(hostGrid, ImgSource, Path.Combine(AppContext.BaseDirectory, $"IconIndex{img.Index}.png"), tw, th);
else
await BitmapHelper.SaveImageSourceToFileAsync(hostGrid, ImgSource, Path.Combine(AppContext.BaseDirectory, $"IconIndex{img.Index}.png"), 32, 32);
}
catch (Exception ex) { Status = $"⚠️ Save: {ex.Message}"; }
}
}
});
}
}
ShowMessage($"Process complete ⇒ {count} total icons", InfoBarSeverity.Informational);
}
else
{
Status = $"⚠️ DLL contained no usable icons";
}
}
catch (Exception ex)
{
Debug.WriteLine($"[ERROR] {ex.Message}");
Status = $"[ERROR] {ex.Message}";
}
finally { IsBusy = false; }
}
else
{
Status = $"⚠️ No results to show";
}
StoryboardPath.Pause();
_ = DispatcherQueue.TryEnqueue(async () =>
{
// Give the UI time to update before saving screen shot. 1ms is adequate, but
// I want plenty of time to pass so the temporary host grid image is no more.
await Task.Delay(500);
await UpdateScreenshot(App.MainRoot ?? hostPage, null);
if (SaveToDisk)
{
await App.ShowDialogBox("Assets", $"Icons have been saved to ⇒ {Environment.NewLine}{Environment.NewLine}{AppContext.BaseDirectory}", "OK", "", null, null, new Uri($"ms-appx:///Assets/Info.png"));
}
});
});
});
// Desktop wallpaper refresh.
TestCommand = new RelayCommand<object>((obj) =>
{
// This was the initial scan that I performed to determine which DLLs contained icon assets.
#region [Testing each DLL in System32]
//var searchDir = System.IO.Path.Combine(Constants.UserEnvironmentPaths.SystemRootPath, "System32");
//if (Directory.Exists(searchDir))
//{
// DirectoryInfo? searchDI = new DirectoryInfo(searchDir);
// FileInfo[]? files = searchDI?.GetFiles("*.dll", SearchOption.TopDirectoryOnly);
// if (files != null)
// {
// StoryboardPath.Resume();
// IsBusy = true;
//
// FileInfo? best = files.OrderByDescending(f => f.LastWriteTime).FirstOrDefault();
// foreach (var file in files)
// {
// var name = file.FullName;
// if (name.Contains("_"))
// continue;
//
// var request = Enumerable.Range(1, 500).ToList();
// Status = $"🔔 Analyzing: {name} ({file.LastWriteTime})";
// IList<IconFileInfo>? fullImageResList = null;
// var extraction = Task.Run(() =>
// {
// fullImageResList = Extensions.ExtractSelectedIconsFromDLL(name, request, 64);
// }).GetAwaiter();
// extraction.OnCompleted(() =>
// {
// if (fullImageResList != null)
// {
// try
// {
// if (fullImageResList.Any())
// {
// foreach (var img in fullImageResList)
// {
// if (img is not null)
// {
// App.DebugLog($"Contains icons ⇒ {Path.GetFileName(name)}");
// break;
// }
// }
// }
// else
// {
// Status = $"⚠️ {name} contained no usable icons";
// }
// }
// catch (Exception ex)
// {
// Debug.WriteLine($"[ERROR] {ex.Message}");
// Status = $"[ERROR] {ex.Message}";
// }
// }
// else
// {
// Status = $"⚠️ No results to show";
// }
// });
// }
//
// IsBusy = false;
// StoryboardPath.Pause();
// }
//}
#endregion
var imgPath = Path.Combine(AppContext.BaseDirectory, $"{App.GetCurrentNamespace()}Screenshot.png");
if (File.Exists(imgPath))
{
// Changes wallpaper to latest screenshot.
_ = App.ShowDialogBox(
"Wallpaper Change",
$"Are you sure you want to change your desktop wallpaper?{Environment.NewLine}{Environment.NewLine}{imgPath.Truncate(51)}",
"Yes",
"Cancel",
() => { _ = SystemParametersInfo(SPI_SETDESKWALLPAPER, 0, imgPath, SPIF_UPDATEINIFILE); Status = "🔔 Wallpaper change accepted by user"; },
() => { Status = "🔔 Wallpaper change canceled by user"; },
new Uri($"ms-appx:///Assets/Notice.png"));
}
uint result = 99;
_ = SystemParametersInfo(SPI_GETFASTTASKSWITCH, 0, ref result, SPIF_UPDATEINIFILE);
Status = $"{(result == 0 ? "Alt-Tab task switching is disabled" : "Alt-Tab task switching is enabled")}";
});
// Dump assemblies.
AboutCommand = new RelayCommand<object>(async (obj) =>
{
try
{
var data = Extensions.GatherLoadedModules(true);
tbAssemblies.Text = data;
contentDialog.XamlRoot = App.MainRoot?.XamlRoot;
await contentDialog.ShowAsync();
}
catch (Exception ex)
{
DispatcherQueue.TryEnqueue(() => Status = $"ERROR: {ex.Message}");
}
});
// Testing IAsyncOperations.
DebugCommand = new RelayCommand<object>(async (obj) =>
{
try
{
IAsyncOperationWithProgress<ulong, ulong>? iaop = PerformDownloadAsync(_cts.Token);
iaop.Progress = (result, prog) =>
{
if (iaop.Status != AsyncStatus.Completed)
DispatcherQueue.TryEnqueue(() => { Status = $"Progress: {prog}%"; });
else
DispatcherQueue.TryEnqueue(() => { Status = $"AsyncStatus: {iaop.Status}"; });
};
var result = await iaop;
DispatcherQueue.TryEnqueue(() => { Status = $"AsyncStatus: {iaop.Status}"; });
}
catch (Exception ex)
{
DispatcherQueue.TryEnqueue(() => Status = $"ERROR: {ex.Message}");
}
});
}
/// <summary>
/// Apply a page's visual state to an <see cref="Microsoft.UI.Xaml.Controls.Image"/> source.
/// If the target is null then the image is saved to disk.
/// </summary>
/// <param name="root">host <see cref="Microsoft.UI.Xaml.UIElement"/>. Can be a grid, a page, etc.</param>
/// <param name="target">optional <see cref="Microsoft.UI.Xaml.Controls.Image"/> target</param>
/// <remarks>
/// Using a RenderTargetBitmap, you can accomplish scenarios such as applying image effects to a visual that
/// originally came from a XAML UI composition, generating thumbnail images of child pages for a navigation
/// system, or enabling the user to save parts of the UI as an image source and then share that image with
/// other applications.
/// Because RenderTargetBitmap is a subclass of <see cref="Microsoft.UI.Xaml.Media.ImageSource"/>,
/// it can be used as the image source for <see cref="Microsoft.UI.Xaml.Controls.Image"/> elements or an
/// <see cref="Microsoft.UI.Xaml.Media.ImageBrush"/> brush.
/// Calling RenderAsync() provides a useful image source but the full buffer representation of rendering
/// content is not copied out of video memory until the app calls GetPixelsAsync().
/// It is faster to call RenderAsync() only, without calling GetPixelsAsync, and use the RenderTargetBitmap as an
/// <see cref="Microsoft.UI.Xaml.Controls.Image"/> or <see cref="Microsoft.UI.Xaml.Media.ImageBrush"/>
/// source if the app only intends to display the rendered content and does not need the pixel data.
/// [Stipulations]
/// - Content that's in the tree but with its Visibility set to Collapsed won't be captured.
/// - Content that's not directly connected to the XAML visual tree and the content of the main window won't be captured. This includes Popup content, which is considered to be like a sub-window.
/// - Content that can't be captured will appear as blank in the captured image, but other content in the same visual tree can still be captured and will render (the presence of content that can't be captured won't invalidate the entire capture of that XAML composition).
/// - Content that's in the XAML visual tree but offscreen can be captured, so long as it's not Visibility = Collapsed.
/// https://learn.microsoft.com/en-us/uwp/api/windows.ui.xaml.media.imaging.rendertargetbitmap?view=winrt-22621
/// </remarks>
async Task UpdateScreenshot(Microsoft.UI.Xaml.UIElement root, Microsoft.UI.Xaml.Controls.Image? target)
{
Microsoft.UI.Xaml.Media.Imaging.RenderTargetBitmap renderTargetBitmap = new();
await renderTargetBitmap.RenderAsync(root, App.m_width, App.m_height);
if (target is not null)
{
// A render target bitmap is a viable ImageSource.
imgCycle.Source = renderTargetBitmap;
}
else
{
// Convert RenderTargetBitmap to SoftwareBitmap
IBuffer pixelBuffer = await renderTargetBitmap.GetPixelsAsync();
byte[] pixels = pixelBuffer.ToArray();
if (pixels.Length == 0 || renderTargetBitmap.PixelWidth == 0 || renderTargetBitmap.PixelHeight == 0)
{
Debug.WriteLine($"[ERROR] The width and height are not valid, cannot save.");
}
else
{
Windows.Graphics.Imaging.SoftwareBitmap softwareBitmap = new Windows.Graphics.Imaging.SoftwareBitmap(Windows.Graphics.Imaging.BitmapPixelFormat.Bgra8, renderTargetBitmap.PixelWidth, renderTargetBitmap.PixelHeight, Windows.Graphics.Imaging.BitmapAlphaMode.Premultiplied);
softwareBitmap.CopyFromBuffer(pixelBuffer);
await softwareBitmap.SaveSoftwareBitmapToFileAsync(Path.Combine(AppContext.BaseDirectory, $"{App.GetCurrentNamespace()}Screenshot.png"), Windows.Graphics.Imaging.BitmapInterpolationMode.NearestNeighbor);
softwareBitmap.Dispose();
}
}
}
async Task<RandomAccessStreamReference> GetRandomAccessStreamFromUIElement(UIElement? element)
{
Microsoft.UI.Xaml.Media.Imaging.RenderTargetBitmap renderTargetBitmap = new();
InMemoryRandomAccessStream stream = new InMemoryRandomAccessStream();
// Render to an image at the current system scale and retrieve pixel contents
await renderTargetBitmap.RenderAsync(element ?? hostPage);
var pixelBuffer = await renderTargetBitmap.GetPixelsAsync();
// Encode image to an in-memory stream.
var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, stream);
encoder.SetPixelData(
BitmapPixelFormat.Bgra8,
BitmapAlphaMode.Ignore,
(uint)renderTargetBitmap.PixelWidth,
(uint)renderTargetBitmap.PixelHeight,
96d,
96d,
pixelBuffer.ToArray());
await encoder.FlushAsync();
// Set content to the encoded image in memory.
return RandomAccessStreamReference.CreateFromStream(stream);
}
void ItemsGridViewOnLoaded(object sender, RoutedEventArgs e)
{
// Delegate loading of icons, so we have smooth navigating to
// this page and do not unnecessarily block the UI thread.
// On startup there won't be anything in the collection, but
// in the event that you decide to load a large number of
// items from disk, this will facilitate that process.
Task.Run(delegate ()
{
_ = DispatcherQueue.TryEnqueue(Microsoft.UI.Dispatching.DispatcherQueuePriority.High, () =>
{
IconsRepeater.ItemsSource = IconItems;
});
});
_loaded = true;
TargetDLL = dlls[0];
Status = "✔️ Ready";
StoryboardPath.Begin();
StoryboardPath.Pause();
ShowMessage(ReflectAssemblyFramework(typeof(MainPage)), InfoBarSeverity.Informational);
#region [Manipulatable Container Test]
//Image img = new Image
//{
// Opacity = 0.8d,
// Width = 40,
// Height = 40,
// Source = new Microsoft.UI.Xaml.Media.Imaging.BitmapImage(new Uri("ms-appx:///Assets/StoreLogo.png", UriKind.RelativeOrAbsolute)),
//};
//Button btn = new Button
//{
// Width = 54,
// Height = 54,
// Padding = new Thickness(0),
// VerticalAlignment = VerticalAlignment.Bottom,
// HorizontalAlignment = HorizontalAlignment.Right,
// Content = img,
//};
//btn.Click += (_, _) => { Status = "you clicked me"; };
//ToolTipService.SetToolTip(btn, "drag me around");
//AddManipulatableElement(btn);
#endregion
}
/// <summary>
/// Makes an element manipulatable and adds it to the host grid.
/// </summary>
/// <param name="element"><see cref="UIElement"/></param>
void AddManipulatableElement(UIElement element)
{
ManipulatableContainer container = new ManipulatableContainer();
container.Content = element;
hostGrid.Children.Add(container);
}
/// <summary>
/// A BitmapImage can be sourced from these image file formats:
/// - Joint Photographic Experts Group (JPEG)
/// - Portable Network Graphics (PNG)
/// - Bitmap (BMP)
/// - Graphics Interchange Format (GIF)
/// - Tagged Image File Format (TIFF)
/// - JPEG XR
/// - Icon (ICO)
/// </summary>
/// <remarks>
/// If the image source is a stream, that stream is expected to contain an image file in one of these formats.
/// The BitmapImage class represents an abstraction so that an image source can be set asynchronously but still
/// be referenced in XAML markup as a property value, or in code as an object that doesn't use awaitable syntax.
/// When you create a BitmapImage object in code, it initially has no valid source. You should then set its source
/// using one of these techniques:
/// Use the BitmapImage(Uri) constructor rather than the default constructor. Although it's a constructor you can
/// think of this as having an implicit asynchronous behavior: the BitmapImage won't be ready for use until it
/// raises an ImageOpened event that indicates a successful async source set operation.
/// Set the UriSource property. As with using the Uri constructor, this action is implicitly asynchronous, and the
/// BitmapImage won't be ready for use until it raises an ImageOpened event.
/// Use SetSourceAsync. This method is explicitly asynchronous. The properties where you might use a BitmapImage,
/// such as Image.Source, are designed for this asynchronous behavior, and won't throw exceptions if they are set
/// using a BitmapImage that doesn't have a complete source yet. Rather than handling exceptions, you should handle
/// ImageOpened or ImageFailed events either on the BitmapImage directly or on the control that uses the source
/// (if those events are available on the control class).
/// ImageFailed and ImageOpened are mutually exclusive. One event or the other will always be raised whenever a
/// BitmapImage object has its source value set or reset.
/// The API for Image, BitmapImage and BitmapSource doesn't include any dedicated methods for encoding and decoding
/// of media formats. All of the encode and decode operations are built-in, and at most will surface aspects of
/// encode or decode as part of event data for load events.
/// If you want to do any special work with image encode or decode, which you might use if your app is doing image
/// conversions or manipulation, you should use the API that are available in the Windows.Graphics.Imaging namespace.
/// </remarks>
void TestImage_Loaded(object sender, RoutedEventArgs e)
{
Image? img = sender as Image;
if (img is null)
return;
Microsoft.UI.Xaml.Media.Imaging.BitmapImage bitmapImage = new Microsoft.UI.Xaml.Media.Imaging.BitmapImage();
// TODO: Try -1 for DecodePixelWidth
img.Width = bitmapImage.DecodePixelWidth = 80;
// Natural px width of image source. You don't need to set DecodePixelHeight because
// the system maintains aspect ratio, and calculates the other dimension, as long as
// one dimension measurement is provided.
bitmapImage.UriSource = new Uri(img.BaseUri, "Assets/StoreLogo.png");
img.Source = bitmapImage;
}
async Task TestBitmapCropper(ImageSource source)
{
if (source is not null)
{
var cropped = await BitmapHelper.GetCroppedBitmap(source as WriteableBitmap, new Point(1, 1), new Size(10, 10), 1d);
//imgCrop.Source = cropped;
}
}
void IconsOnTemplatePointerPressed(object sender, PointerRoutedEventArgs e)
{
var oldIndex = IconItems.IndexOf(SelectedIcon);
var previousItem = IconsRepeater.TryGetElement(oldIndex);
if (previousItem != null) { MoveToSelectionState(previousItem, false); }
var itemIndex = IconsRepeater.GetElementIndex(sender as UIElement);
SelectedIcon = IconItems[itemIndex != -1 ? itemIndex : 0];
MoveToSelectionState(sender as UIElement, true);
}
/// <summary>
/// Activate the proper VisualStateGroup for the control.
/// </summary>
static void MoveToSelectionState(UIElement previousItem, bool isSelected)
{
try { VisualStateManager.GoToState(previousItem as Control, isSelected ? "Selected" : "Default", false); }
catch (NullReferenceException ex) { App.DebugLog($"[{previousItem.NameOf()}] {ex.Message}"); }
}
/// <summary>
/// General helper method.
/// </summary>
IconFileInfo? LoadIconResource(int iconIndex)
{
string imageres = System.IO.Path.Combine(Constants.UserEnvironmentPaths.SystemRootPath, "System32", "imageres.dll");
var imageResList = Extensions.ExtractSelectedIconsFromDLL(
imageres,
new List<int>() { iconIndex },
24);
return imageResList.FirstOrDefault();
}
void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (_loaded)
{
try
{
var selection = e.AddedItems[0] as string;
if (!string.IsNullOrEmpty(selection))
{
TargetDLL = selection;
}
}
catch (Exception ex)
{
Debug.WriteLine($"[ERROR] SelectionChanged: {ex.Message}");
}
}
}
/// <summary>
/// <see cref="TextBox"/> event.
/// </summary>
void TextBox_GotFocus(object sender, RoutedEventArgs e)
{