From 416c7d18edb1dbde4027993ce7498b55b4e3f00d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=AB=98=E6=80=A1=E9=A3=9E?= <363301617@qq.com> Date: Sun, 4 Aug 2024 21:18:44 +0800 Subject: [PATCH] Use SynchronizationContext.Post method to replace BeginInvoke Use SynchronizationContext.Post method to replace BeginInvoke --- .../Extensions/DataType/Enums/MenuType.cs | 23 + WindowsTools/Models/ShellMenuItemModel.cs | 52 +- WindowsTools/Program.cs | 7 +- WindowsTools/Properties/AssemblyInfo.cs | 6 +- WindowsTools/Strings/ShellMenu.Designer.cs | 96 +- WindowsTools/Strings/ShellMenu.en-us.resx | 34 +- WindowsTools/Strings/ShellMenu.resx | 34 +- WindowsTools/Strings/ShellMenu.zh-hans.resx | 31 +- .../UI/Backdrop/DesktopAcrylicBackdrop.cs | 24 +- WindowsTools/UI/Backdrop/MicaBackdrop.cs | 24 +- .../Controls/FirstLevelMenuEditControl.xaml | 1082 ----------------- .../FirstLevelMenuEditControl.xaml.cs | 681 ----------- .../Controls/SecondLevelMenuEditControl.xaml | 779 ------------ .../SecondLevelMenuEditControl.xaml.cs | 573 --------- .../UI/Dialogs/AppInformationDialog.xaml | 1 - .../UI/Dialogs/AppInformationDialog.xaml.cs | 23 +- .../UI/Dialogs/FileCheckDialog.xaml.cs | 7 +- .../UI/Dialogs/RestartAppsDialog.xaml.cs | 8 +- WindowsTools/Views/Pages/AboutPage.xaml.cs | 26 +- .../Views/Pages/CodeScannerPage.xaml.cs | 33 +- .../Views/Pages/DownloadManagerPage.xaml.cs | 43 +- .../Views/Pages/ExtensionNamePage.xaml.cs | 11 +- .../Views/Pages/FileCertificatePage.xaml.cs | 11 +- WindowsTools/Views/Pages/FileNamePage.xaml.cs | 11 +- .../Views/Pages/FilePropertiesPage.xaml.cs | 11 +- .../Views/Pages/FileUnlockPage.xaml.cs | 40 +- .../Views/Pages/IconExtractPage.xaml.cs | 23 +- WindowsTools/Views/Pages/LoafPage.xaml | 1 - WindowsTools/Views/Pages/LoafPage.xaml.cs | 25 +- .../Views/Pages/LoopbackManagerPage.xaml.cs | 19 +- WindowsTools/Views/Pages/MainPage.xaml | 2 + WindowsTools/Views/Pages/MainPage.xaml.cs | 18 +- .../Views/Pages/PriExtractPage.xaml.cs | 36 +- WindowsTools/Views/Pages/ShellMenuPage.xaml | 958 +++++++++++---- .../Views/Pages/ShellMenuPage.xaml.cs | 857 +++++++++++-- .../Views/Pages/SimulateUpdatePage.xaml.cs | 13 +- .../Views/Pages/UpdateManagerPage.xaml.cs | 51 +- .../Views/Pages/UpperAndLowerCasePage.xaml.cs | 11 +- WindowsTools/Views/Pages/WinSATPage.xaml | 1 - WindowsTools/Views/Pages/WinSATPage.xaml.cs | 28 +- .../WindowsAPI/ComTypes/ACTIVATEOPTIONS.cs | 34 + .../ComTypes/BackgroundCopyCallback.cs | 9 +- .../ComTypes/DODownloadStatusCallback.cs | 3 +- .../ComTypes/IApplicationActivationManager.cs | 38 + .../ComTypes/IBackgroundCopyCallback.cs | 8 +- .../ComTypes/IDODownloadStatusCallback.cs | 3 +- .../WindowsAPI/ComTypes/IDOManager.cs | 4 +- .../ComTypes/IDataTransferManagerInterop.cs | 6 +- .../WindowsAPI/ComTypes/IPinnedList3.cs | 4 +- .../WindowsAPI/ComTypes/IProgressDialog.cs | 18 +- .../WindowsAPI/ComTypes/IShellLink.cs | 36 +- WindowsToolsPackage/Package.appxmanifest | 2 +- .../Properties/AssemblyInfo.cs | 6 +- 53 files changed, 1913 insertions(+), 3972 deletions(-) create mode 100644 WindowsTools/Extensions/DataType/Enums/MenuType.cs delete mode 100644 WindowsTools/UI/Controls/FirstLevelMenuEditControl.xaml delete mode 100644 WindowsTools/UI/Controls/FirstLevelMenuEditControl.xaml.cs delete mode 100644 WindowsTools/UI/Controls/SecondLevelMenuEditControl.xaml delete mode 100644 WindowsTools/UI/Controls/SecondLevelMenuEditControl.xaml.cs create mode 100644 WindowsTools/WindowsAPI/ComTypes/ACTIVATEOPTIONS.cs create mode 100644 WindowsTools/WindowsAPI/ComTypes/IApplicationActivationManager.cs diff --git a/WindowsTools/Extensions/DataType/Enums/MenuType.cs b/WindowsTools/Extensions/DataType/Enums/MenuType.cs new file mode 100644 index 0000000..c953c95 --- /dev/null +++ b/WindowsTools/Extensions/DataType/Enums/MenuType.cs @@ -0,0 +1,23 @@ +namespace WindowsTools.Extensions.DataType.Enums +{ + /// + /// 菜单类型 + /// + public enum MenuType + { + /// + /// 根菜单 + /// + RootMenu = 0, + + /// + /// 一级菜单 + /// + FirstLevelMenu = 1, + + /// + /// 二级菜单 + /// + SecondLevelMenu = 2 + } +} diff --git a/WindowsTools/Models/ShellMenuItemModel.cs b/WindowsTools/Models/ShellMenuItemModel.cs index 3e71258..d011018 100644 --- a/WindowsTools/Models/ShellMenuItemModel.cs +++ b/WindowsTools/Models/ShellMenuItemModel.cs @@ -1,5 +1,8 @@ -using System.ComponentModel; +using System; +using System.Collections.ObjectModel; +using System.ComponentModel; using Windows.UI.Xaml.Media; +using WindowsTools.Extensions.DataType.Enums; namespace WindowsTools.Models { @@ -8,6 +11,32 @@ namespace WindowsTools.Models /// public class ShellMenuItemModel : INotifyPropertyChanged { + /// + /// 菜单 Guid 号 + /// + public Guid MenuGuid { get; set; } + + /// + /// 菜单类型 + /// + public MenuType MenuType { get; set; } + + private bool _isSelected; + + public bool IsSelected + { + get { return _isSelected; } + + set + { + if (!Equals(_isSelected, value)) + { + _isSelected = value; + PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(IsSelected))); + } + } + } + /// /// 菜单项索引 /// @@ -19,7 +48,7 @@ public int MenuIndex set { - if (!Equals(value, _menuIndex)) + if (!Equals(_menuIndex, value)) { _menuIndex = value; PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(MenuIndex))); @@ -103,21 +132,10 @@ public string ProgramPath } } - private string _param; - - public string Param - { - get { return _param; } - - set - { - if (!Equals(_param, value)) - { - _param = value; - PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Param))); - } - } - } + /// + /// 子菜单 + /// + public ObservableCollection SubMenuItemCollection { get; set; } = []; public event PropertyChangedEventHandler PropertyChanged; } diff --git a/WindowsTools/Program.cs b/WindowsTools/Program.cs index 71f6724..a182729 100644 --- a/WindowsTools/Program.cs +++ b/WindowsTools/Program.cs @@ -1,5 +1,4 @@ using System; -using System.Diagnostics; using System.Diagnostics.Tracing; using System.Globalization; using System.Threading; @@ -10,6 +9,7 @@ using WindowsTools.Services.Root; using WindowsTools.Services.Shell; using WindowsTools.Views.Windows; +using WindowsTools.WindowsAPI.ComTypes; namespace WindowsTools { @@ -18,6 +18,8 @@ namespace WindowsTools /// public class Program { + private static Guid applicationActivationManagerCLSID = new("45BA127D-10A8-46EA-8AB7-56EA9078943C"); + /// /// 应用程序的主入口点 /// @@ -26,7 +28,8 @@ public static void Main() { if (!RuntimeHelper.IsMSIX) { - Process.Start("explorer.exe", "shell:AppsFolder\\055B5CA4.WindowsTools_zp2hc899bs298!WindowsTools"); + IApplicationActivationManager applicationActivationManager = (IApplicationActivationManager)Activator.CreateInstance(Type.GetTypeFromCLSID(applicationActivationManagerCLSID)); + applicationActivationManager.ActivateApplication("Gaoyifei1011.WindowsTools_pystbwmrmew8c!WindowsTools", string.Empty, ACTIVATEOPTIONS.AO_NONE, out uint _); return; } diff --git a/WindowsTools/Properties/AssemblyInfo.cs b/WindowsTools/Properties/AssemblyInfo.cs index 88a6c83..fc63211 100644 --- a/WindowsTools/Properties/AssemblyInfo.cs +++ b/WindowsTools/Properties/AssemblyInfo.cs @@ -4,8 +4,8 @@ [assembly: AssemblyCompany("高怡飞")] [assembly: AssemblyCopyright("Copyright ©2024 高怡飞, All Rights Reserved.")] [assembly: AssemblyDescription("Windows 工具箱")] -[assembly: AssemblyFileVersion("2.7.801.0")] -[assembly: AssemblyInformationalVersion("2.7.801.0")] +[assembly: AssemblyFileVersion("2.7.804.0")] +[assembly: AssemblyInformationalVersion("2.7.804.0")] [assembly: AssemblyProduct("Windows 工具箱")] [assembly: AssemblyTitle("Windows 工具箱")] -[assembly: AssemblyVersion("2.7.801.0")] +[assembly: AssemblyVersion("2.7.804.0")] diff --git a/WindowsTools/Strings/ShellMenu.Designer.cs b/WindowsTools/Strings/ShellMenu.Designer.cs index 81533a5..c6e1959 100644 --- a/WindowsTools/Strings/ShellMenu.Designer.cs +++ b/WindowsTools/Strings/ShellMenu.Designer.cs @@ -169,29 +169,11 @@ public static string Drive { } /// - /// 查找类似 Edit 的本地化字符串。 + /// 查找类似 Edit menu 的本地化字符串。 /// - public static string Edit { + public static string EditMenu { get { - return ResourceManager.GetString("Edit", resourceCulture); - } - } - - /// - /// 查找类似 There's no menu items 的本地化字符串。 - /// - public static string EmptyDescription { - get { - return ResourceManager.GetString("EmptyDescription", resourceCulture); - } - } - - /// - /// 查找类似 The content of the secondary menu is empty 的本地化字符串。 - /// - public static string EmptySecondLevelMenu { - get { - return ResourceManager.GetString("EmptySecondLevelMenu", resourceCulture); + return ResourceManager.GetString("EditMenu", resourceCulture); } } @@ -204,15 +186,6 @@ public static string Extension { } } - /// - /// 查找类似 First level menu 的本地化字符串。 - /// - public static string FirstLevelMenu { - get { - return ResourceManager.GetString("FirstLevelMenu", resourceCulture); - } - } - /// /// 查找类似 Icon file(*.ico)|*.ico 的本地化字符串。 /// @@ -321,15 +294,6 @@ public static string MenuList { } } - /// - /// 查找类似 Menu order 的本地化字符串。 - /// - public static string MenuOrder { - get { - return ResourceManager.GetString("MenuOrder", resourceCulture); - } - } - /// /// 查找类似 Menu parameter 的本地化字符串。 /// @@ -366,15 +330,6 @@ public static string MenuProgramPathPHText { } } - /// - /// 查找类似 Menu program path: 的本地化字符串。 - /// - public static string MenuProgramPathToolTip { - get { - return ResourceManager.GetString("MenuProgramPathToolTip", resourceCulture); - } - } - /// /// 查找类似 Menu settings 的本地化字符串。 /// @@ -465,15 +420,6 @@ public static string None { } } - /// - /// 查找类似 Operation 的本地化字符串。 - /// - public static string Operation { - get { - return ResourceManager.GetString("Operation", resourceCulture); - } - } - /// /// 查找类似 Precautions 的本地化字符串。 /// @@ -573,15 +519,6 @@ public static string Save { } } - /// - /// 查找类似 Second level menu 的本地化字符串。 - /// - public static string SecondLevelMenu { - get { - return ResourceManager.GetString("SecondLevelMenu", resourceCulture); - } - } - /// /// 查找类似 Select icon 的本地化字符串。 /// @@ -663,33 +600,6 @@ public static string ShouldUseProgramIconOnContent { } } - /// - /// 查找类似 Should use second level menu 的本地化字符串。 - /// - public static string ShouldUseSecondLevelMenu { - get { - return ResourceManager.GetString("ShouldUseSecondLevelMenu", resourceCulture); - } - } - - /// - /// 查找类似 No 的本地化字符串。 - /// - public static string ShouldUseSecondLevelMenuOffContent { - get { - return ResourceManager.GetString("ShouldUseSecondLevelMenuOffContent", resourceCulture); - } - } - - /// - /// 查找类似 Yes 的本地化字符串。 - /// - public static string ShouldUseSecondLevelMenuOnContent { - get { - return ResourceManager.GetString("ShouldUseSecondLevelMenuOnContent", resourceCulture); - } - } - /// /// 查找类似 Custom shell menu 的本地化字符串。 /// diff --git a/WindowsTools/Strings/ShellMenu.en-us.resx b/WindowsTools/Strings/ShellMenu.en-us.resx index cf0b14c..7439f6b 100644 --- a/WindowsTools/Strings/ShellMenu.en-us.resx +++ b/WindowsTools/Strings/ShellMenu.en-us.resx @@ -153,21 +153,12 @@ Drive - - Edit - - - There's no menu items - - - The content of the secondary menu is empty + + Edit menu Extension name - - First level menu - Icon file(*.ico)|*.ico @@ -204,9 +195,6 @@ Menu list - - Menu order - Menu parameter @@ -219,9 +207,6 @@ The application path is not set - - Menu program path: - Menu settings @@ -252,9 +237,6 @@ None - - Operation - Precautions @@ -288,9 +270,6 @@ Save - - Second level menu - Select icon @@ -318,15 +297,6 @@ Yes - - Should use second level menu - - - No - - - Yes - Custom shell menu diff --git a/WindowsTools/Strings/ShellMenu.resx b/WindowsTools/Strings/ShellMenu.resx index cf0b14c..7439f6b 100644 --- a/WindowsTools/Strings/ShellMenu.resx +++ b/WindowsTools/Strings/ShellMenu.resx @@ -153,21 +153,12 @@ Drive - - Edit - - - There's no menu items - - - The content of the secondary menu is empty + + Edit menu Extension name - - First level menu - Icon file(*.ico)|*.ico @@ -204,9 +195,6 @@ Menu list - - Menu order - Menu parameter @@ -219,9 +207,6 @@ The application path is not set - - Menu program path: - Menu settings @@ -252,9 +237,6 @@ None - - Operation - Precautions @@ -288,9 +270,6 @@ Save - - Second level menu - Select icon @@ -318,15 +297,6 @@ Yes - - Should use second level menu - - - No - - - Yes - Custom shell menu diff --git a/WindowsTools/Strings/ShellMenu.zh-hans.resx b/WindowsTools/Strings/ShellMenu.zh-hans.resx index 42970c1..d410f52 100644 --- a/WindowsTools/Strings/ShellMenu.zh-hans.resx +++ b/WindowsTools/Strings/ShellMenu.zh-hans.resx @@ -153,21 +153,15 @@ 驱动器 - - 编辑 + + 编辑菜单 菜单没有任何内容 - - 二级菜单内容为空 - 扩展名称 - - 一级菜单 - 图标文件(*.ico)|*.ico @@ -204,9 +198,6 @@ 菜单列表 - - 菜单顺序 - 菜单参数 @@ -219,9 +210,6 @@ 未设置应用程序路径 - - 菜单程序文件路径: - 菜单设置 @@ -252,9 +240,6 @@ 不匹配 - - 操作 - 注意事项 @@ -288,9 +273,6 @@ 保存 - - 二级菜单 - 选择图标 @@ -318,15 +300,6 @@ - - 是否启用二级菜单 - - - - - - - 自定义扩展菜单 diff --git a/WindowsTools/UI/Backdrop/DesktopAcrylicBackdrop.cs b/WindowsTools/UI/Backdrop/DesktopAcrylicBackdrop.cs index 3858a4e..c732b61 100644 --- a/WindowsTools/UI/Backdrop/DesktopAcrylicBackdrop.cs +++ b/WindowsTools/UI/Backdrop/DesktopAcrylicBackdrop.cs @@ -2,6 +2,7 @@ using System; using System.Numerics; using System.Runtime.InteropServices; +using System.Threading; using System.Windows.Forms; using Windows.UI; using Windows.UI.Composition; @@ -33,6 +34,7 @@ public class DesktopAcrylicBackdrop : SystemBackdrop private readonly Form formRoot; private readonly FrameworkElement rootElement; private readonly CompositionCapabilities compositionCapabilities = CompositionCapabilities.GetForCurrentView(); + private readonly SynchronizationContext synchronizationContext = SynchronizationContext.Current; private readonly float defaultDesktopAcrylicDefaultLightTintOpacity = 0; private readonly float defaultDesktopAcrylicDefaultLightLuminosityOpacity = 0.85f; @@ -478,7 +480,10 @@ public override void Dispose() /// private void OnUserPreferenceChanged(object sender, UserPreferenceChangedEventArgs args) { - formRoot.BeginInvoke(UpdateBrush); + synchronizationContext.Post(_ => + { + UpdateBrush(); + }, null); } /// @@ -486,14 +491,14 @@ private void OnUserPreferenceChanged(object sender, UserPreferenceChangedEventAr /// private void OnSizeChanged(object sender, EventArgs args) { - formRoot.BeginInvoke(() => + synchronizationContext.Post(_ => { SpriteVisual spriteVisual = DesktopWindowTarget.Root as SpriteVisual; if (spriteVisual is not null) { spriteVisual.Size = new Vector2(formRoot.Width, formRoot.Height); } - }); + }, null); } /// @@ -501,14 +506,14 @@ private void OnSizeChanged(object sender, EventArgs args) /// private void OnDpiChanged(object sender, DpiChangedEventArgs args) { - formRoot.BeginInvoke(() => + synchronizationContext.Post(_ => { SpriteVisual spriteVisual = DesktopWindowTarget.Root as SpriteVisual; if (spriteVisual is not null) { spriteVisual.Size = new Vector2(formRoot.Width, formRoot.Height); } - }); + }, null); } /// @@ -546,7 +551,10 @@ private void OnDeactivated(object sender, EventArgs args) /// private void OnCompositionCapabilitiesChanged(CompositionCapabilities sender, object args) { - formRoot.BeginInvoke(UpdateBrush); + synchronizationContext.Post(_ => + { + UpdateBrush(); + }, null); } /// @@ -808,10 +816,10 @@ private IntPtr OnFormSubClassProc(IntPtr hWnd, WindowMessage Msg, UIntPtr wParam if (isInitialized) { - formRoot.BeginInvoke(() => + synchronizationContext.Post(_ => { UpdateBrush(); - }); + }, null); } } } diff --git a/WindowsTools/UI/Backdrop/MicaBackdrop.cs b/WindowsTools/UI/Backdrop/MicaBackdrop.cs index 218d0f3..04b45e7 100644 --- a/WindowsTools/UI/Backdrop/MicaBackdrop.cs +++ b/WindowsTools/UI/Backdrop/MicaBackdrop.cs @@ -2,6 +2,7 @@ using System; using System.Numerics; using System.Runtime.InteropServices; +using System.Threading; using System.Windows.Forms; using Windows.UI; using Windows.UI.Composition; @@ -32,6 +33,7 @@ public class MicaBackdrop : SystemBackdrop private readonly Form formRoot; private readonly FrameworkElement rootElement; private readonly CompositionCapabilities compositionCapabilities = CompositionCapabilities.GetForCurrentView(); + private readonly SynchronizationContext synchronizationContext = SynchronizationContext.Current; private readonly float defaultMicaBaseLightTintOpacity = 0.5f; private readonly float defaultMicaBaseLightLuminosityOpacity = 1; @@ -397,7 +399,10 @@ public override void Dispose() /// private void OnUserPreferenceChanged(object sender, UserPreferenceChangedEventArgs args) { - formRoot.BeginInvoke(UpdateBrush); + synchronizationContext.Post(_ => + { + UpdateBrush(); + }, null); } /// @@ -405,14 +410,14 @@ private void OnUserPreferenceChanged(object sender, UserPreferenceChangedEventAr /// private void OnSizeChanged(object sender, EventArgs args) { - formRoot.BeginInvoke(() => + synchronizationContext.Post(_ => { SpriteVisual spriteVisual = DesktopWindowTarget.Root as SpriteVisual; if (spriteVisual is not null) { spriteVisual.Size = new Vector2(formRoot.Width, formRoot.Height); } - }); + }, null); } /// @@ -420,14 +425,14 @@ private void OnSizeChanged(object sender, EventArgs args) /// private void OnDpiChanged(object sender, DpiChangedEventArgs args) { - formRoot.BeginInvoke(() => + synchronizationContext.Post(_ => { SpriteVisual spriteVisual = DesktopWindowTarget.Root as SpriteVisual; if (spriteVisual is not null) { spriteVisual.Size = new Vector2(formRoot.Width, formRoot.Height); } - }); + }, null); } /// @@ -465,7 +470,10 @@ private void OnDeactivated(object sender, EventArgs args) /// private void OnCompositionCapabilitiesChanged(CompositionCapabilities sender, object args) { - formRoot.BeginInvoke(UpdateBrush); + synchronizationContext.Post(_ => + { + UpdateBrush(); + }, null); } /// @@ -674,10 +682,10 @@ private IntPtr OnFormSubClassProc(IntPtr hWnd, WindowMessage Msg, UIntPtr wParam if (isInitialized) { - formRoot.BeginInvoke(() => + synchronizationContext.Post(_ => { UpdateBrush(); - }); + }, null); } } } diff --git a/WindowsTools/UI/Controls/FirstLevelMenuEditControl.xaml b/WindowsTools/UI/Controls/FirstLevelMenuEditControl.xaml deleted file mode 100644 index ce7b5a1..0000000 --- a/WindowsTools/UI/Controls/FirstLevelMenuEditControl.xaml +++ /dev/null @@ -1,1082 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - public sealed partial class AppInformationDialog : ContentDialog, INotifyPropertyChanged { + private readonly SynchronizationContext synchronizationContext = SynchronizationContext.Current; + private string _windowsAppSDKVersion; public string WindowsAppSDKVersion @@ -111,13 +112,7 @@ public string DoNetVersion public AppInformationDialog() { InitializeComponent(); - } - /// - /// 初始化应用信息 - /// - private void OnLoaded(object sender, RoutedEventArgs args) - { Task.Run(() => { IReadOnlyList dependencyList = Package.Current.Dependencies; @@ -127,14 +122,14 @@ private void OnLoaded(object sender, RoutedEventArgs args) if (dependency.DisplayName.Contains("WindowsAppRuntime")) { // Windows 应用 SDK 版本信息 - MainWindow.Current.Invoke(() => + synchronizationContext.Post(_ => { WindowsAppSDKVersion = string.Format("{0}.{1}.{2}.{3}", dependency.Id.Version.Major, dependency.Id.Version.Minor, dependency.Id.Version.Build, dependency.Id.Version.Revision); - }); + }, null); } // WinUI 2 版本信息 @@ -142,14 +137,14 @@ private void OnLoaded(object sender, RoutedEventArgs args) { FileVersionInfo winUI2File = FileVersionInfo.GetVersionInfo(Path.Combine(dependency.InstalledPath, "Microsoft.UI.Xaml.dll")); - MainWindow.Current.Invoke(() => + synchronizationContext.Post(_ => { WinUI2Version = string.Format("{0}.{1}.{2}.{3}", winUI2File.ProductMajorPart, winUI2File.ProductMinorPart, winUI2File.ProductBuildPart, winUI2File.ProductPrivatePart); - }); + }, null); } } @@ -157,7 +152,7 @@ private void OnLoaded(object sender, RoutedEventArgs args) FileVersionInfo mileXamlFile = FileVersionInfo.GetVersionInfo(Path.Combine(AppContext.BaseDirectory, @"Mile.Xaml.Managed.dll")); - MainWindow.Current.Invoke(() => + synchronizationContext.Post(_ => { WindowsUIVersion = string.Format("{0}.{1}.{2}.{3}", windowsUIFile.ProductMajorPart, @@ -170,7 +165,7 @@ private void OnLoaded(object sender, RoutedEventArgs args) // .NET 版本信息 DoNetVersion = Convert.ToString(RuntimeInformation.FrameworkDescription.Remove(0, 15)); - }); + }, null); }); } diff --git a/WindowsTools/UI/Dialogs/FileCheckDialog.xaml.cs b/WindowsTools/UI/Dialogs/FileCheckDialog.xaml.cs index 5fbc7bf..dad5557 100644 --- a/WindowsTools/UI/Dialogs/FileCheckDialog.xaml.cs +++ b/WindowsTools/UI/Dialogs/FileCheckDialog.xaml.cs @@ -1,13 +1,13 @@ using System; using System.Diagnostics; using System.IO; +using System.Threading; using System.Threading.Tasks; using Windows.UI.Xaml.Controls; using WindowsTools.Extensions.DataType.Enums; using WindowsTools.Helpers.Controls.Extensions; using WindowsTools.Services.Controls.Download; using WindowsTools.UI.TeachingTips; -using WindowsTools.Views.Windows; // 抑制 IDE0060 警告 #pragma warning disable IDE0060 @@ -21,6 +21,7 @@ public sealed partial class FileCheckDialog : ContentDialog { private readonly string downloadUrl; private readonly string downloadFilePath; + private readonly SynchronizationContext synchronizationContext = SynchronizationContext.Current; public FileCheckDialog(string url, string saveFilePath) { @@ -43,10 +44,10 @@ private void OnPrimaryButtonClicked(object sender, ContentDialogButtonClickEvent } catch (Exception) { - MainWindow.Current.BeginInvoke(() => + synchronizationContext.Post(_ => { TeachingTipHelper.Show(new OperationResultTip(OperationKind.DeleteFileFailed)); - }); + }, null); Process.Start(Path.GetDirectoryName(downloadFilePath)); } }); diff --git a/WindowsTools/UI/Dialogs/RestartAppsDialog.xaml.cs b/WindowsTools/UI/Dialogs/RestartAppsDialog.xaml.cs index 88c1f59..27ec5af 100644 --- a/WindowsTools/UI/Dialogs/RestartAppsDialog.xaml.cs +++ b/WindowsTools/UI/Dialogs/RestartAppsDialog.xaml.cs @@ -1,8 +1,8 @@ using System.Diagnostics; +using System.Threading; using System.Threading.Tasks; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; -using WindowsTools.Views.Windows; // 抑制 IDE0060 警告 #pragma warning disable IDE0060 @@ -14,6 +14,8 @@ namespace WindowsTools.UI.Dialogs /// public sealed partial class RestartAppsDialog : ContentDialog { + private readonly SynchronizationContext synchronizationContext = SynchronizationContext.Current; + public RestartAppsDialog() { InitializeComponent(); @@ -27,10 +29,10 @@ private void OnRestartAppsClicked(ContentDialog sender, ContentDialogButtonClick Task.Run(() => { Process.Start(Process.GetCurrentProcess().MainModule.FileName, "Restart"); - MainWindow.Current.BeginInvoke(() => + synchronizationContext.Post(_ => { (Application.Current as App).Dispose(); - }); + }, null); }); } } diff --git a/WindowsTools/Views/Pages/AboutPage.xaml.cs b/WindowsTools/Views/Pages/AboutPage.xaml.cs index b836d4b..4ad3cd3 100644 --- a/WindowsTools/Views/Pages/AboutPage.xaml.cs +++ b/WindowsTools/Views/Pages/AboutPage.xaml.cs @@ -9,6 +9,7 @@ using System.Runtime.InteropServices; using System.Text; using System.Text.RegularExpressions; +using System.Threading; using System.Threading.Tasks; using Windows.ApplicationModel; using Windows.ApplicationModel.Core; @@ -24,7 +25,6 @@ using WindowsTools.UI.Dialogs; using WindowsTools.UI.Dialogs.About; using WindowsTools.UI.TeachingTips; -using WindowsTools.Views.Windows; using WindowsTools.WindowsAPI.ComTypes; using WindowsTools.WindowsAPI.PInvoke.Kernel32; @@ -38,6 +38,11 @@ namespace WindowsTools.Views.Pages /// public sealed partial class AboutPage : Page, INotifyPropertyChanged { + private static Guid taskbarPinCLSID = new("90AA3A4E-1CBA-4233-B8BB-535773D48449"); + private static Guid ishellLinkCLSID = new("00021401-0000-0000-C000-000000000046"); + + private readonly SynchronizationContext synchronizationContext = SynchronizationContext.Current; + private bool _isChecking; public bool IsChecking @@ -54,9 +59,6 @@ public bool IsChecking } } - private static Guid taskbarPinCLSID = new("90AA3A4E-1CBA-4233-B8BB-535773D48449"); - private static Guid ishellLinkCLSID = new("00021401-0000-0000-C000-000000000046"); - //项目引用信息 private List ReferenceDict { get; } = [ @@ -112,10 +114,10 @@ private void OnPinToDesktopClicked(object sender, RoutedEventArgs args) } finally { - MainWindow.Current.BeginInvoke(() => + synchronizationContext.Post(_ => { TeachingTipHelper.Show(new QuickOperationTip(QuickOperationKind.Desktop, isCreatedSuccessfully)); - }); + }, null); } }); } @@ -153,10 +155,10 @@ private async void OnPinToStartScreenClicked(object sender, RoutedEventArgs args } finally { - MainWindow.Current.BeginInvoke(() => + synchronizationContext.Post(_ => { TeachingTipHelper.Show(new QuickOperationTip(QuickOperationKind.StartScreen, isPinnedSuccessfully)); - }); + }, null); } } @@ -303,10 +305,10 @@ private void OnCheckUpdateClicked(object sender, RoutedEventArgs args) { bool isNewest = InfoHelper.AppVersion >= tagVersion; - MainWindow.Current.BeginInvoke(() => + synchronizationContext.Post(_ => { TeachingTipHelper.Show(new OperationResultTip(OperationKind.CheckUpdate, isNewest)); - }); + }, null); } } } @@ -336,10 +338,10 @@ private void OnCheckUpdateClicked(object sender, RoutedEventArgs args) } finally { - MainWindow.Current.BeginInvoke(() => + synchronizationContext.Post(_ => { IsChecking = false; - }); + }, null); } }); } diff --git a/WindowsTools/Views/Pages/CodeScannerPage.xaml.cs b/WindowsTools/Views/Pages/CodeScannerPage.xaml.cs index 17cf557..88219f2 100644 --- a/WindowsTools/Views/Pages/CodeScannerPage.xaml.cs +++ b/WindowsTools/Views/Pages/CodeScannerPage.xaml.cs @@ -9,6 +9,7 @@ using System.Drawing.Printing; using System.IO; using System.Reflection; +using System.Threading; using System.Threading.Tasks; using System.Windows.Forms; using Windows.ApplicationModel.DataTransfer; @@ -22,7 +23,6 @@ using WindowsTools.Services.Root; using WindowsTools.Strings; using WindowsTools.UI.TeachingTips; -using WindowsTools.Views.Windows; using ZXing; using ZXing.Common; using ZXing.QrCode; @@ -38,6 +38,7 @@ namespace WindowsTools.Views.Pages public sealed partial class CodeScannerPage : Page, INotifyPropertyChanged { private readonly BindingFlags bindingFlags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.IgnoreCase | BindingFlags.Static; + private readonly SynchronizationContext synchronizationContext = SynchronizationContext.Current; private PrintPreviewDialog printPreviewDialog; private PrintDialog printDialog; private PrintDocument printDocument; @@ -465,7 +466,7 @@ private void OnGeneratePhotoClicked(object sender, RoutedEventArgs args) barCodeBitmap.Save(memoryStream, ImageFormat.Png); memoryStream.Position = 0; - MainWindow.Current.BeginInvoke(() => + synchronizationContext.Post(_ => { try { @@ -477,13 +478,10 @@ private void OnGeneratePhotoClicked(object sender, RoutedEventArgs args) } catch (Exception e) { - MainWindow.Current.BeginInvoke(() => - { - TeachingTipHelper.Show(new OperationResultTip(OperationKind.GenerateBarCodeFailed)); - }); + TeachingTipHelper.Show(new OperationResultTip(OperationKind.GenerateBarCodeFailed)); LogService.WriteLog(EventLevel.Error, "Display generated bar code photo failed", e); } - }); + }, null); } } // 二维码 @@ -497,7 +495,7 @@ private void OnGeneratePhotoClicked(object sender, RoutedEventArgs args) qrCodeBitmap.Save(memoryStream, ImageFormat.Png); memoryStream.Position = 0; - MainWindow.Current.BeginInvoke(() => + synchronizationContext.Post(_ => { try { @@ -509,13 +507,10 @@ private void OnGeneratePhotoClicked(object sender, RoutedEventArgs args) } catch (Exception e) { - MainWindow.Current.BeginInvoke(() => - { - TeachingTipHelper.Show(new OperationResultTip(OperationKind.GenerateQRCodeFailed)); - }); + TeachingTipHelper.Show(new OperationResultTip(OperationKind.GenerateQRCodeFailed)); LogService.WriteLog(EventLevel.Error, "Display generated qr code photo failed", e); } - }); + }, null); } } }); @@ -752,25 +747,25 @@ public void ParseCodeImage(System.Drawing.Image image) if (result is not null) { - MainWindow.Current.BeginInvoke(() => + synchronizationContext.Post(_ => { RecognizeText = result.Text; - }); + }, null); } else { - MainWindow.Current.BeginInvoke(() => + synchronizationContext.Post(_ => { TeachingTipHelper.Show(new OperationResultTip(OperationKind.ParsePhotoFailed)); - }); + }, null); } } catch (Exception e) { - MainWindow.Current.BeginInvoke(() => + synchronizationContext.Post(_ => { TeachingTipHelper.Show(new OperationResultTip(OperationKind.ParsePhotoFailed)); - }); + }, null); LogService.WriteLog(EventLevel.Error, string.Format("Parse code file failed"), e); } }); diff --git a/WindowsTools/Views/Pages/DownloadManagerPage.xaml.cs b/WindowsTools/Views/Pages/DownloadManagerPage.xaml.cs index 3833f8f..584f274 100644 --- a/WindowsTools/Views/Pages/DownloadManagerPage.xaml.cs +++ b/WindowsTools/Views/Pages/DownloadManagerPage.xaml.cs @@ -8,6 +8,7 @@ using System.Linq; using System.Runtime.InteropServices; using System.Runtime.InteropServices.WindowsRuntime; +using System.Threading; using System.Threading.Tasks; using System.Windows.Forms; using Windows.ApplicationModel.DataTransfer; @@ -40,6 +41,7 @@ namespace WindowsTools.Views.Pages /// public sealed partial class DownloadManagerPage : Page, INotifyPropertyChanged { + private readonly SynchronizationContext synchronizationContext = SynchronizationContext.Current; private bool isAllowClosed = false; private string _searchDownloadText; @@ -297,7 +299,7 @@ private void OnDeleteWithFileExecuteRequested(XamlUICommand sender, ExecuteReque } } - MainWindow.Current.BeginInvoke(() => + synchronizationContext.Post(_ => { foreach (DownloadModel item in DownloadCollection) { @@ -307,7 +309,7 @@ private void OnDeleteWithFileExecuteRequested(XamlUICommand sender, ExecuteReque break; } } - }); + }, null); } }); } @@ -325,8 +327,7 @@ private void OnShareFileExecuteRequested(XamlUICommand sender, ExecuteRequestedE { IDataTransferManagerInterop dataTransferManagerInterop = (IDataTransferManagerInterop)WindowsRuntimeMarshal.GetActivationFactory(typeof(DataTransferManager)); - DataTransferManager dataTransferManager = dataTransferManagerInterop.GetForWindow(MainWindow.Current.Handle, new("A5CAEE9B-8708-49D1-8D36-67D25A8DA00C")); - + dataTransferManagerInterop.GetForWindow(MainWindow.Current.Handle, new("A5CAEE9B-8708-49D1-8D36-67D25A8DA00C"), out DataTransferManager dataTransferManager); dataTransferManager.DataRequested += async (sender, args) => { DataRequestDeferral deferral = args.Request.GetDeferral(); @@ -336,7 +337,7 @@ private void OnShareFileExecuteRequested(XamlUICommand sender, ExecuteRequestedE deferral.Complete(); }; - dataTransferManagerInterop.ShowShareUIForWindow((IntPtr)MainWindow.Current.Handle); + dataTransferManagerInterop.ShowShareUIForWindow(MainWindow.Current.Handle); } catch (Exception e) { @@ -520,7 +521,7 @@ private void OnDownloadSettingsClicked(object sender, RoutedEventArgs args) /// private void OnDownloadCreated(Guid downloadID, DownloadSchedulerModel downloadSchedulerItem) { - MainWindow.Current.BeginInvoke(() => + synchronizationContext.Post(_ => { DownloadCollection.Add(new DownloadModel() { @@ -534,7 +535,7 @@ private void OnDownloadCreated(Guid downloadID, DownloadSchedulerModel downloadS CurrentSpeed = 0, TotalSize = downloadSchedulerItem.TotalSize }); - }); + }, null); } /// @@ -542,7 +543,7 @@ private void OnDownloadCreated(Guid downloadID, DownloadSchedulerModel downloadS /// private void OnDownloadContinued(Guid downloadID) { - MainWindow.Current.BeginInvoke(() => + synchronizationContext.Post(_ => { foreach (DownloadModel downloadItem in DownloadCollection) { @@ -552,7 +553,7 @@ private void OnDownloadContinued(Guid downloadID) downloadItem.DownloadStatus = DownloadStatus.Downloading; } } - }); + }, null); } /// @@ -560,7 +561,7 @@ private void OnDownloadContinued(Guid downloadID) /// private void OnDownloadPaused(Guid downloadID) { - MainWindow.Current.BeginInvoke(() => + synchronizationContext.Post(_ => { foreach (DownloadModel downloadItem in DownloadCollection) { @@ -570,7 +571,7 @@ private void OnDownloadPaused(Guid downloadID) downloadItem.DownloadStatus = DownloadStatus.Pause; } } - }); + }, null); } /// @@ -578,7 +579,7 @@ private void OnDownloadPaused(Guid downloadID) /// private void OnDownloadDeleted(Guid downloadID) { - MainWindow.Current.BeginInvoke(() => + synchronizationContext.Post(_ => { foreach (DownloadModel downloadItem in DownloadCollection) { @@ -588,7 +589,7 @@ private void OnDownloadDeleted(Guid downloadID) break; } } - }); + }, null); } /// @@ -596,7 +597,7 @@ private void OnDownloadDeleted(Guid downloadID) /// private void OnDownloadProgressing(Guid downloadID, DownloadSchedulerModel downloadSchedulerItem) { - MainWindow.Current.BeginInvoke(() => + synchronizationContext.Post(_ => { foreach (DownloadModel downloadItem in DownloadCollection) { @@ -610,7 +611,7 @@ private void OnDownloadProgressing(Guid downloadID, DownloadSchedulerModel downl break; } } - }); + }, null); } /// @@ -618,7 +619,7 @@ private void OnDownloadProgressing(Guid downloadID, DownloadSchedulerModel downl /// private void OnDownloadCompleted(Guid downloadID, DownloadSchedulerModel downloadSchedulerItem) { - MainWindow.Current.BeginInvoke(() => + synchronizationContext.Post(_ => { foreach (DownloadModel downloadItem in DownloadCollection) { @@ -632,7 +633,7 @@ private void OnDownloadCompleted(Guid downloadID, DownloadSchedulerModel downloa break; } } - }); + }, null); } /// @@ -689,11 +690,11 @@ private void OnDownloadLinkTextChanged(object sender, TextChangedEventArgs args) string fileName = uri.Segments[uri.Segments.Length - 1]; if (fileName is not "/") { - MainWindow.Current.BeginInvoke(() => + synchronizationContext.Post(_ => { DownloadFileNameText = fileName; IsPrimaryButtonEnabled = !string.IsNullOrEmpty(DownloadLinkText) && !string.IsNullOrEmpty(DownloadFolderText); - }); + }, null); } } } @@ -762,10 +763,10 @@ private void OnDownloadClicked(object sender, RoutedEventArgs args) // 检查本地文件是否存在 if (File.Exists(filePath)) { - MainWindow.Current.BeginInvoke(async () => + synchronizationContext.Post(async (_) => { await ContentDialogHelper.ShowAsync(new FileCheckDialog(DownloadLinkText, filePath), MainWindow.Current.Content as FrameworkElement); - }); + }, null); } else { diff --git a/WindowsTools/Views/Pages/ExtensionNamePage.xaml.cs b/WindowsTools/Views/Pages/ExtensionNamePage.xaml.cs index 1e6c973..c6c5253 100644 --- a/WindowsTools/Views/Pages/ExtensionNamePage.xaml.cs +++ b/WindowsTools/Views/Pages/ExtensionNamePage.xaml.cs @@ -4,6 +4,7 @@ using System.ComponentModel; using System.Diagnostics.Tracing; using System.IO; +using System.Threading; using System.Threading.Tasks; using System.Windows.Forms; using Windows.ApplicationModel.DataTransfer; @@ -21,7 +22,6 @@ using WindowsTools.Strings; using WindowsTools.UI.Dialogs; using WindowsTools.UI.TeachingTips; -using WindowsTools.Views.Windows; // 抑制 IDE0060 警告 #pragma warning disable IDE0060 @@ -33,6 +33,7 @@ namespace WindowsTools.Views.Pages /// public sealed partial class ExtensionNamePage : Page, INotifyPropertyChanged { + private readonly SynchronizationContext synchronizationContext = SynchronizationContext.Current; private readonly object extensionNameLock = new(); private bool _isModifyingNow = false; @@ -518,7 +519,7 @@ private async void OnViewErrorInformationClicked(object sender, RoutedEventArgs /// public void AddToExtensionNamePage(List extensionNameList) { - MainWindow.Current.BeginInvoke(() => + synchronizationContext.Post(_ => { lock (extensionNameLock) { @@ -527,7 +528,7 @@ public void AddToExtensionNamePage(List extensionNameList) ExtensionNameCollection.Add(oldAndNewNameItem); } } - }); + }, null); } /// @@ -621,7 +622,7 @@ private void ChangeFileName() await Task.Delay(300); - MainWindow.Current.BeginInvoke(() => + synchronizationContext.Post(_ => { IsModifyingNow = false; foreach (OperationFailedModel operationFailedItem in operationFailedList) @@ -635,7 +636,7 @@ private void ChangeFileName() ExtensionNameCollection.Clear(); } - }); + }, null); }); } } diff --git a/WindowsTools/Views/Pages/FileCertificatePage.xaml.cs b/WindowsTools/Views/Pages/FileCertificatePage.xaml.cs index 72fc315..2f19ad2 100644 --- a/WindowsTools/Views/Pages/FileCertificatePage.xaml.cs +++ b/WindowsTools/Views/Pages/FileCertificatePage.xaml.cs @@ -5,6 +5,7 @@ using System.Diagnostics.Tracing; using System.IO; using System.Runtime.InteropServices; +using System.Threading; using System.Threading.Tasks; using System.Windows.Forms; using Windows.ApplicationModel.DataTransfer; @@ -22,7 +23,6 @@ using WindowsTools.Strings; using WindowsTools.UI.Dialogs; using WindowsTools.UI.TeachingTips; -using WindowsTools.Views.Windows; using WindowsTools.WindowsAPI.PInvoke.Imagehlp; // 抑制 IDE0060 警告 @@ -35,6 +35,7 @@ namespace WindowsTools.Views.Pages /// public sealed partial class FileCertificatePage : Page, INotifyPropertyChanged { + private readonly SynchronizationContext synchronizationContext = SynchronizationContext.Current; private readonly object fileCertificateLock = new(); private bool _isModifyingNow = false; @@ -312,7 +313,7 @@ private async void OnViewErrorInformationClicked(object sender, RoutedEventArgs /// public void AddToFileCertificatePage(List fileCertificateList) { - MainWindow.Current.BeginInvoke(() => + synchronizationContext.Post(_ => { lock (fileCertificateLock) { @@ -321,7 +322,7 @@ public void AddToFileCertificatePage(List fileCertificat FileCertificateCollection.Add(certificateResultItem); } } - }); + }, null); } /// @@ -369,7 +370,7 @@ private void RemoveFileCertificates() await Task.Delay(300); - MainWindow.Current.BeginInvoke(() => + synchronizationContext.Post(_ => { IsModifyingNow = false; foreach (OperationFailedModel operationFailedItem in operationFailedList) @@ -383,7 +384,7 @@ private void RemoveFileCertificates() FileCertificateCollection.Clear(); } - }); + }, null); }); } } diff --git a/WindowsTools/Views/Pages/FileNamePage.xaml.cs b/WindowsTools/Views/Pages/FileNamePage.xaml.cs index 1b851c7..9b4208d 100644 --- a/WindowsTools/Views/Pages/FileNamePage.xaml.cs +++ b/WindowsTools/Views/Pages/FileNamePage.xaml.cs @@ -5,6 +5,7 @@ using System.ComponentModel; using System.Diagnostics.Tracing; using System.IO; +using System.Threading; using System.Threading.Tasks; using System.Windows.Forms; using Windows.ApplicationModel.DataTransfer; @@ -22,7 +23,6 @@ using WindowsTools.Strings; using WindowsTools.UI.Dialogs; using WindowsTools.UI.TeachingTips; -using WindowsTools.Views.Windows; // 抑制 IDE0060 警告 #pragma warning disable IDE0060 @@ -34,6 +34,7 @@ namespace WindowsTools.Views.Pages /// public sealed partial class FileNamePage : Page, INotifyPropertyChanged { + private readonly SynchronizationContext synchronizationContext = SynchronizationContext.Current; private readonly object fileNameLock = new(); private bool _isChecked = false; @@ -700,7 +701,7 @@ private async void OnViewErrorInformationClicked(object sender, RoutedEventArgs /// public void AddToFileNamePage(List filenameList) { - MainWindow.Current.BeginInvoke(() => + synchronizationContext.Post(_ => { lock (fileNameLock) { @@ -709,7 +710,7 @@ public void AddToFileNamePage(List filenameList) FileNameCollection.Add(oldAndNewNameItem); } } - }); + }, null); } private string GetChangeRule(int index) @@ -903,7 +904,7 @@ private void ChangeFileName() await Task.Delay(300); - MainWindow.Current.BeginInvoke(() => + synchronizationContext.Post(_ => { IsModifyingNow = false; foreach (OperationFailedModel operationFailedItem in operationFailedList) @@ -917,7 +918,7 @@ private void ChangeFileName() FileNameCollection.Clear(); } - }); + }, null); }); } } diff --git a/WindowsTools/Views/Pages/FilePropertiesPage.xaml.cs b/WindowsTools/Views/Pages/FilePropertiesPage.xaml.cs index 966fa99..582c2ca 100644 --- a/WindowsTools/Views/Pages/FilePropertiesPage.xaml.cs +++ b/WindowsTools/Views/Pages/FilePropertiesPage.xaml.cs @@ -5,6 +5,7 @@ using System.Diagnostics.Tracing; using System.IO; using System.Text; +using System.Threading; using System.Threading.Tasks; using System.Windows.Forms; using Windows.ApplicationModel.DataTransfer; @@ -21,7 +22,6 @@ using WindowsTools.Strings; using WindowsTools.UI.Dialogs; using WindowsTools.UI.TeachingTips; -using WindowsTools.Views.Windows; // 抑制 IDE0060 警告 #pragma warning disable IDE0060 @@ -33,6 +33,7 @@ namespace WindowsTools.Views.Pages /// public sealed partial class FilePropertiesPage : Page, INotifyPropertyChanged { + private readonly SynchronizationContext synchronizationContext = SynchronizationContext.Current; private readonly object filePropertiesLock = new(); private bool _isReadOnlyChecked = false; @@ -628,7 +629,7 @@ private async void OnViewErrorInformationClicked(object sender, RoutedEventArgs /// public void AddToFilePropertiesPage(List filePropertiesList) { - MainWindow.Current.BeginInvoke(() => + synchronizationContext.Post(_ => { lock (filePropertiesLock) { @@ -637,7 +638,7 @@ public void AddToFilePropertiesPage(List filePropertie FilePropertiesCollection.Add(oldAndNewPropertiesItem); } } - }); + }, null); } /// @@ -742,7 +743,7 @@ private void ChangeFileAttributes() await Task.Delay(300); - MainWindow.Current.BeginInvoke(() => + synchronizationContext.Post(_ => { IsModifyingNow = false; foreach (OperationFailedModel operationFailedItem in operationFailedList) @@ -756,7 +757,7 @@ private void ChangeFileAttributes() FilePropertiesCollection.Clear(); } - }); + }, null); }); } } diff --git a/WindowsTools/Views/Pages/FileUnlockPage.xaml.cs b/WindowsTools/Views/Pages/FileUnlockPage.xaml.cs index dcb1016..701e79f 100644 --- a/WindowsTools/Views/Pages/FileUnlockPage.xaml.cs +++ b/WindowsTools/Views/Pages/FileUnlockPage.xaml.cs @@ -10,6 +10,7 @@ using System.IO; using System.Linq; using System.Management; +using System.Threading; using System.Threading.Tasks; using System.Windows.Forms; using Windows.ApplicationModel.DataTransfer; @@ -24,7 +25,6 @@ using WindowsTools.Services.Root; using WindowsTools.Strings; using WindowsTools.UI.TeachingTips; -using WindowsTools.Views.Windows; using WindowsTools.WindowsAPI.PInvoke.Rstrtmgr; using WindowsTools.WindowsAPI.PInvoke.Shell32; @@ -38,6 +38,8 @@ namespace WindowsTools.Views.Pages /// public sealed partial class FileUnlockPage : Page, INotifyPropertyChanged { + private readonly SynchronizationContext synchronizationContext = SynchronizationContext.Current; + private InfoBarSeverity _resultSeverity = InfoBarSeverity.Informational; public InfoBarSeverity ResultSeverity @@ -175,10 +177,10 @@ protected override void OnDrop(global::Windows.UI.Xaml.DragEventArgs args) if (filesList.Count is 1) { - MainWindow.Current.BeginInvoke(() => + synchronizationContext.Post(_ => { ParseFile(filesList[0].Path); - }); + }, null); } } } @@ -210,7 +212,7 @@ private void OnTerminateProcessExecuteRequested(XamlUICommand sender, ExecuteReq Process process = Process.GetProcessById(processid); process?.Kill(); - MainWindow.Current.BeginInvoke(() => + synchronizationContext.Post(_ => { foreach (ProcessInfoModel processItem in ProcessInfoCollection) { @@ -222,15 +224,15 @@ private void OnTerminateProcessExecuteRequested(XamlUICommand sender, ExecuteReq } TeachingTipHelper.Show(new OperationResultTip(OperationKind.TerminateProcess, true)); - }); + }, null); } catch (Exception e) { LogService.WriteLog(EventLevel.Error, string.Format("Terminate process id {0} failed", processid), e); - MainWindow.Current.BeginInvoke(() => + synchronizationContext.Post(_ => { TeachingTipHelper.Show(new OperationResultTip(OperationKind.TerminateProcess, false)); - }); + }, null); } }); } @@ -333,12 +335,12 @@ public void ParseFile(string filePath) if (result is not 0) { await Task.Delay(500); - MainWindow.Current.BeginInvoke(() => + synchronizationContext.Post(_ => { ResultSeverity = InfoBarSeverity.Error; IsRingActive = false; StateInfoText = string.Format(FileUnlock.ParseFileFailed, FileName); - }); + }, null); } try @@ -353,12 +355,12 @@ public void ParseFile(string filePath) if (result is not 0) { await Task.Delay(500); - MainWindow.Current.BeginInvoke(() => + synchronizationContext.Post(_ => { ResultSeverity = InfoBarSeverity.Error; IsRingActive = false; StateInfoText = string.Format(FileUnlock.ParseFileFailed, FileName); - }); + }, null); } result = RstrtmgrLibrary.RmGetList(handle, out uint pnProcInfoNeeded, ref pnProcInfo, null, ref lpdwRebootReasons); @@ -390,13 +392,13 @@ public void ParseFile(string filePath) if (processList.Count is 0) { await Task.Delay(500); - MainWindow.Current.BeginInvoke(() => + synchronizationContext.Post(_ => { ResultControlVisable = true; ResultSeverity = InfoBarSeverity.Success; IsRingActive = false; StateInfoText = string.Format(FileUnlock.ParseFileSuccessfully, FileName); - }); + }, null); } else { @@ -408,7 +410,7 @@ public void ParseFile(string filePath) } await Task.Delay(500); - MainWindow.Current.BeginInvoke(() => + synchronizationContext.Post(_ => { ResultControlVisable = true; ResultSeverity = InfoBarSeverity.Success; @@ -441,32 +443,32 @@ public void ParseFile(string filePath) continue; } } - }); + }, null); } } // 解析成功,文件没有被占用 else { await Task.Delay(500); - MainWindow.Current.BeginInvoke(() => + synchronizationContext.Post(_ => { ResultControlVisable = true; ResultSeverity = InfoBarSeverity.Success; IsRingActive = false; StateInfoText = string.Format(FileUnlock.ParseFileSuccessfully, FileName); - }); + }, null); } } catch (Exception) { await Task.Delay(500); - MainWindow.Current.BeginInvoke(() => + synchronizationContext.Post(_ => { ResultControlVisable = false; ResultSeverity = InfoBarSeverity.Error; IsRingActive = false; StateInfoText = string.Format(FileUnlock.ParseFileFailed, FileName); - }); + }, null); } }); } diff --git a/WindowsTools/Views/Pages/IconExtractPage.xaml.cs b/WindowsTools/Views/Pages/IconExtractPage.xaml.cs index 0a0dfe3..76445d7 100644 --- a/WindowsTools/Views/Pages/IconExtractPage.xaml.cs +++ b/WindowsTools/Views/Pages/IconExtractPage.xaml.cs @@ -8,6 +8,7 @@ using System.Drawing.Imaging; using System.IO; using System.Linq; +using System.Threading; using System.Threading.Tasks; using System.Windows.Forms; using Windows.ApplicationModel.DataTransfer; @@ -22,7 +23,6 @@ using WindowsTools.Services.Root; using WindowsTools.Strings; using WindowsTools.UI.TeachingTips; -using WindowsTools.Views.Windows; using WindowsTools.WindowsAPI.PInvoke.User32; // 抑制 IDE0060 警告 @@ -35,6 +35,7 @@ namespace WindowsTools.Views.Pages /// public sealed partial class IconExtractPage : Page, INotifyPropertyChanged { + private readonly SynchronizationContext synchronizationContext = SynchronizationContext.Current; private readonly object iconExtractLock = new(); private string filePath; @@ -264,10 +265,10 @@ protected override void OnDrop(global::Windows.UI.Xaml.DragEventArgs args) if (filesList.Count is 1) { - MainWindow.Current.BeginInvoke(() => + synchronizationContext.Post(_ => { ParseIconFile(filesList[0].Path); - }); + }, null); } } } @@ -476,11 +477,11 @@ private void OnExportSelectedIconsClicked(object sender, RoutedEventArgs args) await Task.Delay(300); - MainWindow.Current.BeginInvoke(() => + synchronizationContext.Post(_ => { IsSaving = false; TeachingTipHelper.Show(new OperationResultTip(OperationKind.IconExtract, selectedItemsList.Count - saveFailedCount, saveFailedCount)); - }); + }, null); }); } } @@ -555,14 +556,14 @@ private void OnExportAllIconsClicked(object sender, RoutedEventArgs args) await Task.Delay(300); - MainWindow.Current.BeginInvoke(() => + synchronizationContext.Post(_ => { lock (iconExtractLock) { IsSaving = false; TeachingTipHelper.Show(new OperationResultTip(OperationKind.IconExtract, IconCollection.Count - saveFailedCount, saveFailedCount)); } - }); + }, null); }); } } @@ -610,7 +611,7 @@ public void ParseIconFile(string iconFilePath) User32Library.DestroyIcon(phicon[index]); } - MainWindow.Current.BeginInvoke(() => + synchronizationContext.Post(_ => { try { @@ -640,17 +641,17 @@ public void ParseIconFile(string iconFilePath) { LogService.WriteLog(EventLevel.Error, string.Format("Display {0} icons failed", iconsList), e); } - }); + }, null); } catch (Exception e) { - MainWindow.Current.BeginInvoke(() => + synchronizationContext.Post(_ => { GetResults = string.Format(IconExtract.GetResults, Path.GetFileName(filePath), 0); NoResources = string.Format(IconExtract.NoResources, Path.GetFileName(filePath)); ImageSource = null; IsImageEmpty = true; - }); + }, null); LogService.WriteLog(EventLevel.Error, string.Format("Parse {0} file icons failed", filePath), e); } diff --git a/WindowsTools/Views/Pages/LoafPage.xaml b/WindowsTools/Views/Pages/LoafPage.xaml index 700ed55..2c0c494 100644 --- a/WindowsTools/Views/Pages/LoafPage.xaml +++ b/WindowsTools/Views/Pages/LoafPage.xaml @@ -53,7 +53,6 @@ diff --git a/WindowsTools/Views/Pages/LoafPage.xaml.cs b/WindowsTools/Views/Pages/LoafPage.xaml.cs index df2147b..2ba56b8 100644 --- a/WindowsTools/Views/Pages/LoafPage.xaml.cs +++ b/WindowsTools/Views/Pages/LoafPage.xaml.cs @@ -5,6 +5,7 @@ using System.Diagnostics.Tracing; using System.IO; using System.Net.Http; +using System.Threading; using System.Threading.Tasks; using System.Windows.Forms; using Windows.Storage.Streams; @@ -26,6 +27,8 @@ namespace WindowsTools.Views.Pages /// public sealed partial class LoafPage : Page, INotifyPropertyChanged { + private readonly SynchronizationContext synchronizationContext = SynchronizationContext.Current; + private bool _loadImageCompleted = false; public bool LoadImageCompleted @@ -150,15 +153,7 @@ public LoafPage() { InitializeComponent(); SelectedUpdateStyle = UpdateStyleList[0]; - } - #region 第一部分:摸鱼页面——挂载的事件 - - /// - /// 加载每日必应壁纸图片 - /// - private void OnLoaded(object sender, RoutedEventArgs args) - { Task.Run(async () => { try @@ -175,7 +170,7 @@ private void OnLoaded(object sender, RoutedEventArgs args) Stream stream = await responseMessage.Content.ReadAsStreamAsync(); IRandomAccessStream randomAccessStream = stream.AsRandomAccessStream(); - MainWindow.Current.BeginInvoke(async () => + synchronizationContext.Post(async (_) => { try { @@ -192,29 +187,31 @@ private void OnLoaded(object sender, RoutedEventArgs args) LoadImageCompleted = true; LogService.WriteLog(EventLevel.Error, "Load bing wallpaper image failed", e); } - }); + }, null); } else { - MainWindow.Current.BeginInvoke(() => + synchronizationContext.Post(_ => { LoafImage = new(new Uri("ms-appx:///Assets/Images/LoafWallpaper.jpg")); LoadImageCompleted = true; - }); + }, null); } } catch (Exception e) { LogService.WriteLog(EventLevel.Error, "Load bing wallpaper image failed", e); - MainWindow.Current.BeginInvoke(() => + synchronizationContext.Post(_ => { LoafImage = new(new Uri("ms-appx:///Assets/Images/LoafWallpaper.jpg")); LoadImageCompleted = true; - }); + }, null); } }); } + #region 第一部分:摸鱼页面——挂载的事件 + /// /// 开始摸鱼 /// diff --git a/WindowsTools/Views/Pages/LoopbackManagerPage.xaml.cs b/WindowsTools/Views/Pages/LoopbackManagerPage.xaml.cs index 3ae760c..e8d4e3e 100644 --- a/WindowsTools/Views/Pages/LoopbackManagerPage.xaml.cs +++ b/WindowsTools/Views/Pages/LoopbackManagerPage.xaml.cs @@ -8,6 +8,7 @@ using System.Runtime.InteropServices; using System.Security.Principal; using System.Text; +using System.Threading; using System.Threading.Tasks; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; @@ -18,7 +19,6 @@ using WindowsTools.Services.Root; using WindowsTools.Strings; using WindowsTools.UI.TeachingTips; -using WindowsTools.Views.Windows; using WindowsTools.WindowsAPI.PInvoke.FirewallAPI; using WindowsTools.WindowsAPI.PInvoke.Shlwapi; @@ -32,6 +32,7 @@ namespace WindowsTools.Views.Pages /// public sealed partial class LoopbackManagerPage : Page, INotifyPropertyChanged { + private readonly SynchronizationContext synchronizationContext = SynchronizationContext.Current; private IntPtr pACs; private bool _isLoadCompleted; @@ -405,10 +406,10 @@ private async Task GetLoopbackDataAsync() IsOldChecked = isEnabled, }; - MainWindow.Current.BeginInvoke(() => + synchronizationContext.Post(_ => { LoopbackCollection.Add(loopbackItem); - }); + }, null); } catch (Exception) { @@ -417,10 +418,10 @@ private async Task GetLoopbackDataAsync() } await Task.Delay(500); - MainWindow.Current.BeginInvoke(() => + synchronizationContext.Post(_ => { IsLoadCompleted = true; - }); + }, null); } /// @@ -521,17 +522,17 @@ private void SetLoopbackState(List loopbackList) if (FirewallAPILibrary.NetworkIsolationSetAppContainerConfig(loopbackList.Count, sidAndAttributesArray) is 0) { - MainWindow.Current.BeginInvoke(() => + synchronizationContext.Post(_ => { TeachingTipHelper.Show(new OperationResultTip(OperationKind.LoopbackSetResult, true)); - }); + }, null); } else { - MainWindow.Current.BeginInvoke(() => + synchronizationContext.Post(_ => { TeachingTipHelper.Show(new OperationResultTip(OperationKind.LoopbackSetResult, false)); - }); + }, null); } } } diff --git a/WindowsTools/Views/Pages/MainPage.xaml b/WindowsTools/Views/Pages/MainPage.xaml index e3ba44f..6277a94 100644 --- a/WindowsTools/Views/Pages/MainPage.xaml +++ b/WindowsTools/Views/Pages/MainPage.xaml @@ -12,6 +12,7 @@ ActualThemeChanged="{x:Bind OnActualThemeChanged}" RequestedTheme="{x:Bind WindowTheme, Mode=OneWay}" mc:Ignorable="d"> + diff --git a/WindowsTools/Views/Pages/MainPage.xaml.cs b/WindowsTools/Views/Pages/MainPage.xaml.cs index 7cdd66e1..c1642a7 100644 --- a/WindowsTools/Views/Pages/MainPage.xaml.cs +++ b/WindowsTools/Views/Pages/MainPage.xaml.cs @@ -4,6 +4,7 @@ using System.Diagnostics.Tracing; using System.IO; using System.Linq; +using System.Threading; using System.Threading.Tasks; using System.Windows.Forms; using Windows.System; @@ -27,6 +28,8 @@ namespace WindowsTools.Views.Pages /// public sealed partial class MainPage : Page, INotifyPropertyChanged { + private readonly SynchronizationContext synchronizationContext = SynchronizationContext.Current; + private ElementTheme _windowTheme; public ElementTheme WindowTheme @@ -425,13 +428,10 @@ public void NavigationFrom() { ShellMenuPage shellMenuPage = (MainNavigationView.Content as Frame).Content as ShellMenuPage; - if (shellMenuPage is not null) + if (shellMenuPage is not null && shellMenuPage.BreadCollection is not null && shellMenuPage.BreadCollection.Count > 1) { - if (shellMenuPage.BreadCollection is not null && shellMenuPage.BreadCollection.Count > 1) - { - shellMenuPage.BreadCollection.RemoveAt(shellMenuPage.BreadCollection.Count - 1); - return; - } + shellMenuPage.BreadCollection.RemoveAt(shellMenuPage.BreadCollection.Count - 1); + return; } if ((MainNavigationView.Content as Frame).CanGoBack) @@ -652,10 +652,10 @@ public void SendReceivedFilesList(List filesList) System.Drawing.Image image = System.Drawing.Image.FromFile(filesList[0]); if (image is not null) { - MainWindow.Current.BeginInvoke(() => + synchronizationContext.Post(_ => { page.ParseCodeImage(image); - }); + }, null); } } catch (Exception e) @@ -677,7 +677,7 @@ public void SendReceivedFilesList(List filesList) private bool GetWindowMaximizeState(bool isWindowMaximized, bool isWindowMaximizeEnabled, string isReverse) { - return isWindowMaximizeEnabled ? isReverse == nameof(isReverse) ? isWindowMaximized.Equals(false) : isWindowMaximized : false; + return isWindowMaximizeEnabled && (isReverse == nameof(isReverse) ? isWindowMaximized.Equals(false) : isWindowMaximized); } } } diff --git a/WindowsTools/Views/Pages/PriExtractPage.xaml.cs b/WindowsTools/Views/Pages/PriExtractPage.xaml.cs index 5c5938c..5a00e23 100644 --- a/WindowsTools/Views/Pages/PriExtractPage.xaml.cs +++ b/WindowsTools/Views/Pages/PriExtractPage.xaml.cs @@ -9,6 +9,7 @@ using System.IO; using System.Linq; using System.Text; +using System.Threading; using System.Threading.Tasks; using System.Windows.Forms; using Windows.ApplicationModel.DataTransfer; @@ -25,7 +26,6 @@ using WindowsTools.Services.Root; using WindowsTools.Strings; using WindowsTools.UI.TeachingTips; -using WindowsTools.Views.Windows; using WindowsTools.WindowsAPI.PInvoke.Shell32; // 抑制 IDE0060 警告 @@ -38,6 +38,8 @@ namespace WindowsTools.Views.Pages /// public sealed partial class PriExtractPage : Page, INotifyPropertyChanged { + private readonly SynchronizationContext synchronizationContext = SynchronizationContext.Current; + private bool isStringAllSelect = false; private bool isFilePathAllSelect = false; private bool isEmbeddedDataAllSelect = false; @@ -298,20 +300,20 @@ protected override void OnDrop(global::Windows.UI.Xaml.DragEventArgs args) if (filesList.Count is 1) { - MainWindow.Current.BeginInvoke(() => + synchronizationContext.Post(_ => { ParseResourceFile(filesList[0].Path); - }); + }, null); } } } catch (Exception e) { LogService.WriteLog(EventLevel.Warning, "Drop file in pri extract page failed", e); - MainWindow.Current.BeginInvoke(() => + synchronizationContext.Post(_ => { IsProcessing = false; - }); + }, null); } }); deferral.Complete(); @@ -386,10 +388,10 @@ private void OnEmbeddedDataExecuteRequested(XamlUICommand sender, ExecuteRequest LogService.WriteLog(EventLevel.Error, string.Format("Open saved embedded data folder {0} failed", dialog.SelectedPath), e); } - MainWindow.Current.BeginInvoke(() => + synchronizationContext.Post(_ => { IsProcessing = false; - }); + }, null); }); } } @@ -579,13 +581,13 @@ private void OnSelectionChnaged(object sender, SelectionChangedEventArgs args) { List coincidentStringList = stringList.Where(item => item.Language.Equals(LanguageCollection[SelectedIndex].Value as string, StringComparison.OrdinalIgnoreCase)).ToList(); - MainWindow.Current.BeginInvoke(() => + synchronizationContext.Post(_ => { foreach (StringModel stringItem in coincidentStringList) { StringCollection.Add(stringItem); } - }); + }, null); }); } @@ -703,10 +705,10 @@ private void OnExportSelectedEmbeddedDataClicked(object sender, RoutedEventArgs LogService.WriteLog(EventLevel.Error, string.Format("Open saved embedded data folder {0} failed", dialog.SelectedPath), e); } - MainWindow.Current.BeginInvoke(() => + synchronizationContext.Post(_ => { IsProcessing = false; - }); + }, null); }); } else @@ -791,10 +793,10 @@ private void OnExportAllEmbeddedDataClicked(object sender, RoutedEventArgs args) LogService.WriteLog(EventLevel.Error, string.Format("Open saved embedded data folder {0} failed", dialog.SelectedPath), e); } - MainWindow.Current.BeginInvoke(() => + synchronizationContext.Post(_ => { IsProcessing = false; - }); + }, null); }); } } @@ -1204,7 +1206,7 @@ public void ParseResourceFile(string filePath) embeddedDataList.Sort((item1, item2) => item1.Key.CompareTo(item2.Key)); // 显示获取到的所有内容 - MainWindow.Current.BeginInvoke(() => + synchronizationContext.Post(_ => { LanguageCollection.Add(new DictionaryEntry(PriExtract.AllLanguage, "AllLanguage")); @@ -1234,18 +1236,18 @@ public void ParseResourceFile(string filePath) IsProcessing = false; GetResults = string.Format(PriExtract.GetResults, Path.GetFileName(filePath), stringList.Count + filePathList.Count + embeddedDataList.Count); isLoadCompleted = true; - }); + }, null); } catch (Exception e) { LogService.WriteLog(EventLevel.Error, string.Format("Parse file {0} resources failed", filePath), e); - MainWindow.Current.BeginInvoke(() => + synchronizationContext.Post(_ => { IsProcessing = false; GetResults = string.Format(PriExtract.GetResults, Path.GetFileName(filePath), 0); isLoadCompleted = true; - }); + }, null); return; } diff --git a/WindowsTools/Views/Pages/ShellMenuPage.xaml b/WindowsTools/Views/Pages/ShellMenuPage.xaml index c687f84..ed092cc 100644 --- a/WindowsTools/Views/Pages/ShellMenuPage.xaml +++ b/WindowsTools/Views/Pages/ShellMenuPage.xaml @@ -5,19 +5,14 @@ xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:muxc="using:Microsoft.UI.Xaml.Controls" + xmlns:sys="using:System" xmlns:collection="using:System.Collections" xmlns:converter="using:WindowsTools.Helpers.Converters" xmlns:model="using:WindowsTools.Models" xmlns:string="using:WindowsTools.Strings" - xmlns:control="using:WindowsTools.UI.Controls" NavigationCacheMode="Enabled" mc:Ignorable="d"> - - - - - @@ -79,7 +74,6 @@ Visibility="{x:Bind converter:ValueCheckConverterHelper.IsCurrentControl(BreadCollection.Count, 1), Mode=OneWay}"> - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +