diff --git a/About/App.xaml.cs b/About/App.xaml.cs
index e368894..83ef96c 100644
--- a/About/App.xaml.cs
+++ b/About/App.xaml.cs
@@ -3,32 +3,31 @@
// To learn more about WinUI, the WinUI project structure,
// and more about our project templates, see: http://aka.ms/winui-project-info.
-namespace Rebound.About
+namespace Rebound.About;
+
+///
+/// Provides application-specific behavior to supplement the default Application class.
+///
+public partial class App : Application
{
///
- /// Provides application-specific behavior to supplement the default Application class.
+ /// Initializes the singleton application object. This is the first line of authored code
+ /// executed, and as such is the logical equivalent of main() or WinMain().
///
- public partial class App : Application
+ public App()
{
- ///
- /// Initializes the singleton application object. This is the first line of authored code
- /// executed, and as such is the logical equivalent of main() or WinMain().
- ///
- public App()
- {
- this.InitializeComponent();
- }
-
- ///
- /// Invoked when the application is launched.
- ///
- /// Details about the launch request and process.
- protected override void OnLaunched(Microsoft.UI.Xaml.LaunchActivatedEventArgs args)
- {
- m_window = new MainWindow();
- m_window.Activate();
- }
+ this.InitializeComponent();
+ }
- private Window m_window;
+ ///
+ /// Invoked when the application is launched.
+ ///
+ /// Details about the launch request and process.
+ protected override void OnLaunched(Microsoft.UI.Xaml.LaunchActivatedEventArgs args)
+ {
+ m_window = new MainWindow();
+ m_window.Activate();
}
+
+ private Window m_window;
}
diff --git a/About/MainWindow.xaml.cs b/About/MainWindow.xaml.cs
index fb8e75c..14cd589 100644
--- a/About/MainWindow.xaml.cs
+++ b/About/MainWindow.xaml.cs
@@ -6,143 +6,134 @@
using Microsoft.UI.Xaml;
using Microsoft.UI.Xaml.Media;
using Microsoft.Win32;
-using Windows.ApplicationModel.DataTransfer;
using WinUIEx;
-namespace Rebound.About
+namespace Rebound.About;
+
+public sealed partial class MainWindow : WindowEx
{
- public sealed partial class MainWindow : WindowEx
+ public MainWindow()
{
- public MainWindow()
- {
- this.InitializeComponent();
- this.AppWindow.DefaultTitleBarShouldMatchAppModeTheme = true;
- this.IsMaximizable = false;
- this.IsMinimizable = false;
- this.MinWidth = 650;
- this.MoveAndResize(25, 25, 650, 690);
- this.Title = "About Windows";
- this.IsResizable = false;
- this.SystemBackdrop = new MicaBackdrop();
- this.SetIcon($"{AppContext.BaseDirectory}\\Assets\\Rebound.ico");
- User.Text = GetCurrentUserName();
- Version.Text = GetDetailedWindowsVersion();
- LegalStuff.Text = GetLegalInfo();
- Load();
- }
+ this.InitializeComponent();
+ AppWindow.DefaultTitleBarShouldMatchAppModeTheme = true;
+ IsMaximizable = false;
+ IsMinimizable = false;
+ MinWidth = 650;
+ this.MoveAndResize(25, 25, 650, 690);
+ Title = "About Windows";
+ IsResizable = false;
+ SystemBackdrop = new MicaBackdrop();
+ this.SetIcon($"{AppContext.BaseDirectory}\\Assets\\Rebound.ico");
+ User.Text = GetCurrentUserName();
+ Version.Text = GetDetailedWindowsVersion();
+ LegalStuff.Text = GetLegalInfo();
+ Load();
+ }
- public async void Load()
- {
- await Task.Delay(100);
+ public async void Load()
+ {
+ await Task.Delay(100);
- this.SetWindowSize(WinverPanel.ActualWidth + 60, 690);
- }
+ this.SetWindowSize(WinverPanel.ActualWidth + 60, 690);
+ }
- public static string GetDetailedWindowsVersion()
+ public static string GetDetailedWindowsVersion()
+ {
+ try
{
- try
+ // Open the registry key
+ using var key = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows NT\CurrentVersion");
+ if (key != null)
{
- // Open the registry key
- using (var key = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows NT\CurrentVersion"))
- {
- if (key != null)
- {
- // Retrieve build number and revision
- var versionName = key.GetValue("DisplayVersion", "Unknown") as string;
- var buildNumber = key.GetValue("CurrentBuildNumber", "Unknown") as string;
- var buildLab = key.GetValue("UBR", "Unknown");
-
- return $"Version {versionName} (OS Build {buildNumber}.{buildLab})";
- }
- }
- }
- catch (Exception ex)
- {
- return $"Error retrieving OS version details: {ex.Message}";
- }
+ // Retrieve build number and revision
+ var versionName = key.GetValue("DisplayVersion", "Unknown") as string;
+ var buildNumber = key.GetValue("CurrentBuildNumber", "Unknown") as string;
+ var buildLab = key.GetValue("UBR", "Unknown");
- return "Registry key not found";
+ return $"Version {versionName} (OS Build {buildNumber}.{buildLab})";
+ }
+ }
+ catch (Exception ex)
+ {
+ return $"Error retrieving OS version details: {ex.Message}";
}
- public string GetLegalInfo()
+ return "Registry key not found";
+ }
+
+ public string GetLegalInfo()
+ {
+ try
{
- try
- {
- var searcher = new ManagementObjectSearcher("SELECT * FROM Win32_OperatingSystem");
+ var searcher = new ManagementObjectSearcher("SELECT * FROM Win32_OperatingSystem");
- foreach (ManagementObject os in searcher.Get().Cast())
- {
- var caption = os["Caption"];
- var version = os["Version"];
- var buildNumber = os["BuildNumber"];
+ foreach (var os in searcher.Get().Cast())
+ {
+ var caption = os["Caption"];
+ var version = os["Version"];
+ var buildNumber = os["BuildNumber"];
- if (caption.ToString().Contains("10")) windowsVer = "Windows 10";
- else windowsVer = "Windows 11";
+ windowsVer = caption.ToString().Contains("10") ? "Windows 10" : "Windows 11";
- WindowsVer.Text = caption.ToString().Replace("Microsoft ", "");
+ WindowsVer.Text = caption.ToString().Replace("Microsoft ", "");
- return $"The {caption.ToString().Replace("Microsoft ", "")} operating system and its user interface are protected by trademark and other pending or existing intellectual property rights in the United States and other countries/regions.";
- }
+ return $"The {caption.ToString().Replace("Microsoft ", "")} operating system and its user interface are protected by trademark and other pending or existing intellectual property rights in the United States and other countries/regions.";
}
- catch (Exception ex)
- {
- return $"Error retrieving OS edition details: {ex.Message}";
- }
-
- return "WMI query returned no results";
}
+ catch (Exception ex)
+ {
+ return $"Error retrieving OS edition details: {ex.Message}";
+ }
+
+ return "WMI query returned no results";
+ }
- public static string GetCurrentUserName()
+ public static string GetCurrentUserName()
+ {
+ try
{
- try
+ // Open the registry key
+ using var key = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows NT\CurrentVersion");
+ if (key != null)
{
- // Open the registry key
- using (var key = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows NT\CurrentVersion"))
- {
- if (key != null)
- {
- // Retrieve current username
- var owner = key.GetValue("RegisteredOwner", "Unknown") as string;
-
- return owner;
- }
- }
- }
- catch (Exception ex)
- {
- return $"Error retrieving OS version details: {ex.Message}";
- }
+ // Retrieve current username
+ var owner = key.GetValue("RegisteredOwner", "Unknown") as string;
- return "Registry key not found";
+ return owner;
+ }
+ }
+ catch (Exception ex)
+ {
+ return $"Error retrieving OS version details: {ex.Message}";
}
- private async void Button_Click(object sender, RoutedEventArgs e)
+ return "Registry key not found";
+ }
+
+ private async void Button_Click(object sender, RoutedEventArgs e)
+ {
+ var info = new ProcessStartInfo()
{
- var info = new ProcessStartInfo()
- {
- FileName = "powershell",
- Arguments = "winver",
- UseShellExecute = false,
- CreateNoWindow = true
- };
+ FileName = "powershell",
+ Arguments = "winver",
+ UseShellExecute = false,
+ CreateNoWindow = true
+ };
- var proc = Process.Start(info);
+ var proc = Process.Start(info);
- await proc.WaitForExitAsync();
+ await proc.WaitForExitAsync();
- Close();
- }
+ Close();
+ }
- private void Button_Click_1(object sender, RoutedEventArgs e)
- {
- Close();
- }
+ private void Button_Click_1(object sender, RoutedEventArgs e) => Close();
- string windowsVer = "Windows";
+ private string windowsVer = "Windows";
- private void Button_Click_2(object sender, RoutedEventArgs e)
- {
- string content = $@"==========================
+ private void Button_Click_2(object sender, RoutedEventArgs e)
+ {
+ var content = $@"==========================
---Microsoft {windowsVer}---
==========================
@@ -160,9 +151,8 @@ This product is licensed under the [Microsoft Software License Terms] (https://s
{ReboundVer.Text}
Rebound 11 is a Windows mod that does not interfere with the system. The current Windows installation contains additional apps to run Rebound 11.";
- var package = new DataPackage();
- package.SetText(content);
- Clipboard.SetContent(package);
- }
+ var package = new DataPackage();
+ package.SetText(content);
+ Clipboard.SetContent(package);
}
}
diff --git a/Cleanup/App.xaml.cs b/Cleanup/App.xaml.cs
index d1f0c2b..67102aa 100644
--- a/Cleanup/App.xaml.cs
+++ b/Cleanup/App.xaml.cs
@@ -6,40 +6,39 @@
// To learn more about WinUI, the WinUI project structure,
// and more about our project templates, see: http://aka.ms/winui-project-info.
-namespace Rebound.Cleanup
+namespace Rebound.Cleanup;
+
+///
+/// Provides application-specific behavior to supplement the default Application class.
+///
+public partial class App : Application
{
///
- /// Provides application-specific behavior to supplement the default Application class.
+ /// Initializes the singleton application object. This is the first line of authored code
+ /// executed, and as such is the logical equivalent of main() or WinMain().
///
- public partial class App : Application
+ public App()
{
- ///
- /// Initializes the singleton application object. This is the first line of authored code
- /// executed, and as such is the logical equivalent of main() or WinMain().
- ///
- public App()
- {
- this.InitializeComponent();
- }
+ this.InitializeComponent();
+ }
- ///
- /// Invoked when the application is launched.
- ///
- /// Details about the launch request and process.
- protected override async void OnLaunched(Microsoft.UI.Xaml.LaunchActivatedEventArgs args)
- {
- string commandArgs = string.Join(" ", Environment.GetCommandLineArgs().Skip(1));
+ ///
+ /// Invoked when the application is launched.
+ ///
+ /// Details about the launch request and process.
+ protected async override void OnLaunched(Microsoft.UI.Xaml.LaunchActivatedEventArgs args)
+ {
+ var commandArgs = string.Join(" ", Environment.GetCommandLineArgs().Skip(1));
- m_window = new MainWindow(commandArgs);
- m_window.Activate();
+ m_window = new MainWindow(commandArgs);
+ m_window.Activate();
- if (string.IsNullOrEmpty(commandArgs) != true)
- {
- await Task.Delay(100);
- await (m_window as MainWindow).ArgumentsLaunch(commandArgs.Substring(0, 2));
- }
+ if (string.IsNullOrEmpty(commandArgs) != true)
+ {
+ await Task.Delay(100);
+ await (m_window as MainWindow).ArgumentsLaunch(commandArgs[..2]);
}
-
- private Window m_window;
}
+
+ private Window m_window;
}
diff --git a/Cleanup/DiskWindow.xaml.cs b/Cleanup/DiskWindow.xaml.cs
index 7103beb..6cf6089 100644
--- a/Cleanup/DiskWindow.xaml.cs
+++ b/Cleanup/DiskWindow.xaml.cs
@@ -8,1055 +8,1059 @@
using System.Threading.Tasks;
using Microsoft.UI.Xaml;
using Microsoft.UI.Xaml.Controls;
-using Windows.System;
using WinUIEx;
// To learn more about WinUI, the WinUI project structure,
// and more about our project templates, see: http://aka.ms/winui-project-info.
-namespace Rebound.Cleanup
+namespace Rebound.Cleanup;
+
+public class CleanItem
{
- public class CleanItem
+ public string Name
{
- public string Name
- {
- get; set;
- }
- public string ImagePath
- {
- get; set;
- }
- public string ItemPath
+ get; set;
+ }
+ public string ImagePath
+ {
+ get; set;
+ }
+ public string ItemPath
+ {
+ get; set;
+ }
+ public string Description
+ {
+ get; set;
+ }
+ public string DisplaySize
+ {
+ get; set;
+ }
+ public long Size
+ {
+ get; set;
+ }
+ public bool IsChecked
+ {
+ get; set;
+ }
+}
+
+///
+/// An empty window that can be used on its own or navigated to within a Frame.
+///
+public sealed partial class DiskWindow : WindowEx
+{
+ public long GetFolderLongSize(string folderPath)
+ {
+ // Check if the directory exists
+ if (!Directory.Exists(folderPath))
{
- get; set;
+ return 0;
}
- public string Description
+
+ long totalSize = 0;
+ try
{
- get; set;
+ // Enumerate files and directories
+ foreach (var file in EnumerateFiles(folderPath))
+ {
+ try
+ {
+ var fileInfo = new FileInfo(file);
+ totalSize += fileInfo.Length;
+ }
+ catch (UnauthorizedAccessException)
+ {
+ // Skip files we cannot access
+ }
+ catch (IOException)
+ {
+ // Handle other IO exceptions
+ }
+ }
}
- public string DisplaySize
+ catch (UnauthorizedAccessException)
{
- get; set;
+ return 0;
}
- public long Size
+ catch (IOException)
{
- get; set;
+ return 0;
}
- public bool IsChecked
+ catch (Exception)
{
- get; set;
+ return 0;
}
+
+ // Format the size into appropriate units
+ return totalSize;
}
- ///
- /// An empty window that can be used on its own or navigated to within a Frame.
- ///
- public sealed partial class DiskWindow : WindowEx
+ private void CleanupDriverStore()
{
- public long GetFolderLongSize(string folderPath)
+ try
{
- // Check if the directory exists
- if (!Directory.Exists(folderPath))
- {
- return 0;
- }
+ var driverStorePath = @"C:\Windows\System32\DriverStore\FileRepository";
- long totalSize = 0;
+ // Fetch all directories in the DriverStore
+ var directories = Directory.GetDirectories(driverStorePath);
- try
+ foreach (var dir in directories)
{
- // Enumerate files and directories
- foreach (var file in EnumerateFiles(folderPath))
+ // Check if the directory is unused or old
+ // In this example, we assume that if a directory was last accessed over 30 days ago, it's unnecessary.
+ var lastAccessTime = Directory.GetLastAccessTime(dir);
+ if (lastAccessTime < DateTime.Now.AddDays(-30))
{
try
{
- FileInfo fileInfo = new FileInfo(file);
- totalSize += fileInfo.Length;
- }
- catch (UnauthorizedAccessException)
- {
- // Skip files we cannot access
+ Directory.Delete(dir, true);
+ Debug.WriteLine($"Deleted: {dir}");
}
- catch (IOException ex)
+ catch (Exception ex)
{
- // Handle other IO exceptions
+ Debug.WriteLine($"Error deleting {dir}: {ex.Message}");
}
}
}
- catch (UnauthorizedAccessException)
- {
- return 0;
- }
- catch (IOException ex)
- {
- return 0;
- }
- catch (Exception ex)
- {
- return 0;
- }
- // Format the size into appropriate units
- return totalSize;
+ Debug.WriteLine("Driver Store Cleanup Completed.");
}
-
- private void CleanupDriverStore()
+ catch (Exception ex)
{
- try
- {
- string driverStorePath = @"C:\Windows\System32\DriverStore\FileRepository";
+ Debug.WriteLine($"An error occurred during cleanup: {ex.Message}");
+ }
+ }
- // Fetch all directories in the DriverStore
- var directories = Directory.GetDirectories(driverStorePath);
+ public long GetFolderLongSizeDrivers(string folderPath)
+ {
+ // Check if the directory exists
+ if (!Directory.Exists(folderPath))
+ {
+ return 0;
+ }
- foreach (var dir in directories)
+ long totalSize = 0;
+ try
+ {
+ // Enumerate files and directories
+ foreach (var file in EnumerateFiles(folderPath))
+ {
+ try
{
- // Check if the directory is unused or old
- // In this example, we assume that if a directory was last accessed over 30 days ago, it's unnecessary.
- var lastAccessTime = Directory.GetLastAccessTime(dir);
- if (lastAccessTime < DateTime.Now.AddDays(-30))
+ var fileInfo = new FileInfo(file);
+ if (fileInfo.LastAccessTime < DateTime.Now.AddDays(-30))
{
- try
- {
- Directory.Delete(dir, true);
- Debug.WriteLine($"Deleted: {dir}");
- }
- catch (Exception ex)
- {
- Debug.WriteLine($"Error deleting {dir}: {ex.Message}");
- }
+ totalSize += fileInfo.Length;
}
}
-
- Debug.WriteLine("Driver Store Cleanup Completed.");
- }
- catch (Exception ex)
- {
- Debug.WriteLine($"An error occurred during cleanup: {ex.Message}");
+ catch (UnauthorizedAccessException)
+ {
+ // Skip files we cannot access
+ }
+ catch (IOException)
+ {
+ // Handle other IO exceptions
+ }
}
}
-
- public long GetFolderLongSizeDrivers(string folderPath)
+ catch (UnauthorizedAccessException)
{
- // Check if the directory exists
- if (!Directory.Exists(folderPath))
- {
- return 0;
- }
+ return 0;
+ }
+ catch (IOException)
+ {
+ return 0;
+ }
+ catch (Exception)
+ {
+ return 0;
+ }
+
+ // Format the size into appropriate units
+ return totalSize;
+ }
- long totalSize = 0;
+ public string GetFolderSizeDrivers(string folderPath)
+ {
+ // Check if the directory exists
+ if (!Directory.Exists(folderPath))
+ {
+ return "0 B";
+ }
- try
+ long totalSize = 0;
+ try
+ {
+ // Enumerate files and directories
+ foreach (var file in EnumerateFiles(folderPath))
{
- // Enumerate files and directories
- foreach (var file in EnumerateFiles(folderPath))
+ try
{
- try
- {
- FileInfo fileInfo = new FileInfo(file);
- if (fileInfo.LastAccessTime < DateTime.Now.AddDays(-30)) totalSize += fileInfo.Length;
- }
- catch (UnauthorizedAccessException)
- {
- // Skip files we cannot access
- }
- catch (IOException ex)
+ var fileInfo = new FileInfo(file);
+ if (fileInfo.LastAccessTime < DateTime.Now.AddDays(-30))
{
- // Handle other IO exceptions
+ totalSize += fileInfo.Length;
}
}
+ catch (UnauthorizedAccessException)
+ {
+ // Skip files we cannot access
+ }
+ catch (IOException)
+ {
+ // Handle other IO exceptions
+ }
}
- catch (UnauthorizedAccessException)
- {
- return 0;
- }
- catch (IOException ex)
- {
- return 0;
- }
- catch (Exception ex)
- {
- return 0;
- }
-
- // Format the size into appropriate units
- return totalSize;
}
-
- public string GetFolderSizeDrivers(string folderPath)
+ catch (UnauthorizedAccessException)
{
- // Check if the directory exists
- if (!Directory.Exists(folderPath))
- {
- return "0 B";
- }
+ return "0 B";
+ }
+ catch (IOException)
+ {
+ return "0 B";
+ }
+ catch (Exception)
+ {
+ return "0 B";
+ }
- long totalSize = 0;
+ // Format the size into appropriate units
+ return FormatSize(totalSize);
+ }
+
+ public long GetFolderLongSizeDB(string folderPath)
+ {
+ // Check if the directory exists
+ if (!Directory.Exists(folderPath))
+ {
+ return 0;
+ }
- try
+ long totalSize = 0;
+ try
+ {
+ // Enumerate files and directories
+ foreach (var file in EnumerateFiles(folderPath))
{
- // Enumerate files and directories
- foreach (var file in EnumerateFiles(folderPath))
+ try
{
- try
- {
- FileInfo fileInfo = new FileInfo(file);
- if (fileInfo.LastAccessTime < DateTime.Now.AddDays(-30)) totalSize += fileInfo.Length;
- }
- catch (UnauthorizedAccessException)
- {
- // Skip files we cannot access
- }
- catch (IOException ex)
+ var fileInfo = new FileInfo(file);
+ if (fileInfo.Extension.Contains("db") && fileInfo.Name.Contains("thumbcache") == true)
{
- // Handle other IO exceptions
+ totalSize += fileInfo.Length;
}
}
+ catch (UnauthorizedAccessException)
+ {
+ // Skip files we cannot access
+ }
+ catch (IOException)
+ {
+ // Handle other IO exceptions
+ }
}
- catch (UnauthorizedAccessException)
- {
- return "0 B";
- }
- catch (IOException ex)
- {
- return "0 B";
- }
- catch (Exception ex)
- {
- return "0 B";
- }
-
- // Format the size into appropriate units
- return FormatSize(totalSize);
}
-
- public long GetFolderLongSizeDB(string folderPath)
+ catch (UnauthorizedAccessException)
{
- // Check if the directory exists
- if (!Directory.Exists(folderPath))
- {
- return 0;
- }
+ return 0;
+ }
+ catch (IOException)
+ {
+ return 0;
+ }
+ catch (Exception)
+ {
+ return 0;
+ }
+
+ // Format the size into appropriate units
+ return totalSize;
+ }
- long totalSize = 0;
+ public string GetFolderSize(string folderPath)
+ {
+ // Check if the directory exists
+ if (!Directory.Exists(folderPath))
+ {
+ return "0 B";
+ }
- try
+ long totalSize = 0;
+ try
+ {
+ // Enumerate files and directories
+ foreach (var file in EnumerateFiles(folderPath))
{
- // Enumerate files and directories
- foreach (var file in EnumerateFiles(folderPath))
+ try
{
- try
- {
- FileInfo fileInfo = new FileInfo(file);
- if (fileInfo.Extension.Contains("db") && fileInfo.Name.Contains("thumbcache") == true) totalSize += fileInfo.Length;
- }
- catch (UnauthorizedAccessException)
- {
- // Skip files we cannot access
- }
- catch (IOException ex)
- {
- // Handle other IO exceptions
- }
+ var fileInfo = new FileInfo(file);
+ totalSize += fileInfo.Length;
+ }
+ catch (UnauthorizedAccessException)
+ {
+ // Skip files we cannot access
+ }
+ catch (IOException)
+ {
+ // Handle other IO exceptions
}
}
- catch (UnauthorizedAccessException)
- {
- return 0;
- }
- catch (IOException ex)
- {
- return 0;
- }
- catch (Exception ex)
- {
- return 0;
- }
-
- // Format the size into appropriate units
- return totalSize;
}
-
- public string GetFolderSize(string folderPath)
+ catch (UnauthorizedAccessException)
{
- // Check if the directory exists
- if (!Directory.Exists(folderPath))
- {
- return "0 B";
- }
+ return "Access Denied";
+ }
+ catch (IOException)
+ {
+ return "IO Error";
+ }
+ catch (Exception)
+ {
+ return "Unknown Error";
+ }
+
+ // Format the size into appropriate units
+ return FormatSize(totalSize);
+ }
- long totalSize = 0;
+ public void DeleteFiles(string folderPath)
+ {
+ // Check if the directory exists
+ if (!Directory.Exists(folderPath))
+ {
+ return;
+ }
- try
+ try
+ {
+ // Enumerate files and directories
+ foreach (var file in EnumerateFiles(folderPath))
{
- // Enumerate files and directories
- foreach (var file in EnumerateFiles(folderPath))
+ try
{
- try
- {
- FileInfo fileInfo = new FileInfo(file);
- totalSize += fileInfo.Length;
- }
- catch (UnauthorizedAccessException)
- {
- // Skip files we cannot access
- }
- catch (IOException ex)
- {
- // Handle other IO exceptions
- }
+ File.Delete(file);
+ }
+ catch (UnauthorizedAccessException)
+ {
+ // Skip files we cannot access
+ }
+ catch (IOException)
+ {
+ // Handle other IO exceptions
}
}
- catch (UnauthorizedAccessException)
- {
- return "Access Denied";
- }
- catch (IOException ex)
- {
- return "IO Error";
- }
- catch (Exception ex)
- {
- return "Unknown Error";
- }
-
- // Format the size into appropriate units
- return FormatSize(totalSize);
}
+ catch (UnauthorizedAccessException)
+ {
+ return;
+ }
+ catch (IOException)
+ {
+ return;
+ }
+ catch (Exception)
+ {
+ return;
+ }
+ }
- public void DeleteFiles(string folderPath)
+ public void DeleteFilesDB(string folderPath)
+ {
+ // Check if the directory exists
+ if (!Directory.Exists(folderPath))
{
- // Check if the directory exists
- if (!Directory.Exists(folderPath))
- {
- return;
- }
+ return;
+ }
- try
+ try
+ {
+ // Enumerate files and directories
+ foreach (var file in EnumerateFiles(folderPath))
{
- // Enumerate files and directories
- foreach (var file in EnumerateFiles(folderPath))
+ try
{
- try
+ var fileInfo = new FileInfo(file);
+ if (fileInfo.Extension.Contains("db") && fileInfo.Name.Contains("thumbcache") == true)
{
File.Delete(file);
}
- catch (UnauthorizedAccessException)
- {
- // Skip files we cannot access
- }
- catch (IOException ex)
- {
- // Handle other IO exceptions
- }
+ }
+ catch (UnauthorizedAccessException)
+ {
+ // Skip files we cannot access
+ }
+ catch (IOException)
+ {
+ // Handle other IO exceptions
}
}
- catch (UnauthorizedAccessException)
- {
- return;
- }
- catch (IOException ex)
- {
- return;
- }
- catch (Exception ex)
- {
- return;
- }
}
+ catch (UnauthorizedAccessException)
+ {
+ return;
+ }
+ catch (IOException)
+ {
+ return;
+ }
+ catch (Exception)
+ {
+ return;
+ }
+ }
- public void DeleteFilesDB(string folderPath)
+ public string GetFolderSizeDB(string folderPath)
+ {
+ // Check if the directory exists
+ if (!Directory.Exists(folderPath))
{
- // Check if the directory exists
- if (!Directory.Exists(folderPath))
- {
- return;
- }
+ return "0 B";
+ }
- try
+ long totalSize = 0;
+ try
+ {
+ // Enumerate files and directories
+ foreach (var file in EnumerateFiles(folderPath))
{
- // Enumerate files and directories
- foreach (var file in EnumerateFiles(folderPath))
+ try
{
- try
- {
- FileInfo fileInfo = new FileInfo(file);
- if (fileInfo.Extension.Contains("db") && fileInfo.Name.Contains("thumbcache") == true) File.Delete(file);
- }
- catch (UnauthorizedAccessException)
- {
- // Skip files we cannot access
- }
- catch (IOException ex)
+ var fileInfo = new FileInfo(file);
+ Debug.WriteLine($"NAME: {fileInfo.Name} || EXTENSION: {fileInfo.Extension}");
+ if (fileInfo.Extension.Contains("db") && fileInfo.Name.Contains("thumbcache") == true)
{
- // Handle other IO exceptions
+ totalSize += fileInfo.Length;
}
}
+ catch (UnauthorizedAccessException)
+ {
+ Debug.WriteLine("ERR");
+ // Skip files we cannot access
+ }
+ catch (IOException)
+ {
+ Debug.WriteLine("ERR");
+ // Handle other IO exceptions
+ }
}
- catch (UnauthorizedAccessException)
- {
- return;
- }
- catch (IOException ex)
- {
- return;
- }
- catch (Exception ex)
- {
- return;
- }
}
+ catch (UnauthorizedAccessException)
+ {
+ return "Access Denied";
+ }
+ catch (IOException)
+ {
+ return "IO Error";
+ }
+ catch (Exception)
+ {
+ return "Unknown Error";
+ }
+
+ // Format the size into appropriate units
+ return FormatSize(totalSize);
+ }
+
+ private IEnumerable EnumerateFiles(string folderPath)
+ {
+ var directoriesToProcess = new Stack(new[] { folderPath });
- public string GetFolderSizeDB(string folderPath)
+ while (directoriesToProcess.Count > 0)
{
- // Check if the directory exists
- if (!Directory.Exists(folderPath))
+ var currentDir = directoriesToProcess.Pop();
+
+ var files = GetFilesSafe(currentDir);
+ foreach (var file in files)
{
- return "0 B";
+ yield return file;
}
- long totalSize = 0;
-
- try
+ var subDirs = GetDirectoriesSafe(currentDir);
+ foreach (var subDir in subDirs)
{
- // Enumerate files and directories
- foreach (var file in EnumerateFiles(folderPath))
- {
- try
- {
- FileInfo fileInfo = new FileInfo(file);
- Debug.WriteLine($"NAME: {fileInfo.Name} || EXTENSION: {fileInfo.Extension}");
- if (fileInfo.Extension.Contains("db") && fileInfo.Name.Contains("thumbcache") == true) totalSize += fileInfo.Length;
- }
- catch (UnauthorizedAccessException)
- {
- Debug.WriteLine("ERR");
- // Skip files we cannot access
- }
- catch (IOException ex)
- {
- Debug.WriteLine("ERR");
- // Handle other IO exceptions
- }
- }
+ directoriesToProcess.Push(subDir);
}
- catch (UnauthorizedAccessException)
- {
- return "Access Denied";
- }
- catch (IOException ex)
- {
- return "IO Error";
- }
- catch (Exception ex)
- {
- return "Unknown Error";
- }
-
- // Format the size into appropriate units
- return FormatSize(totalSize);
}
+ }
- private IEnumerable EnumerateFiles(string folderPath)
+ private IEnumerable GetFilesSafe(string directory)
+ {
+ try
{
- var directoriesToProcess = new Stack(new[] { folderPath });
-
- while (directoriesToProcess.Count > 0)
- {
- string currentDir = directoriesToProcess.Pop();
-
- IEnumerable files = GetFilesSafe(currentDir);
- foreach (string file in files)
- {
- yield return file;
- }
-
- IEnumerable subDirs = GetDirectoriesSafe(currentDir);
- foreach (string subDir in subDirs)
- {
- directoriesToProcess.Push(subDir);
- }
- }
+ return Directory.EnumerateFiles(directory);
}
-
- private IEnumerable GetFilesSafe(string directory)
+ catch (UnauthorizedAccessException)
{
- try
- {
- return Directory.EnumerateFiles(directory);
- }
- catch (UnauthorizedAccessException)
- {
- // Skip directories we cannot access
- return Array.Empty();
- }
- catch (IOException ex)
- {
- // Handle IO exceptions for directory operations
- return Array.Empty();
- }
+ // Skip directories we cannot access
+ return Array.Empty();
}
-
- private IEnumerable GetDirectoriesSafe(string directory)
+ catch (IOException)
{
- try
- {
- return Directory.EnumerateDirectories(directory);
- }
- catch (UnauthorizedAccessException)
- {
- // Skip directories we cannot access
- return Array.Empty();
- }
- catch (IOException ex)
- {
- // Handle IO exceptions for directory operations
- return Array.Empty();
- }
+ // Handle IO exceptions for directory operations
+ return Array.Empty();
}
+ }
- private string FormatSize(long sizeInBytes)
+ private IEnumerable GetDirectoriesSafe(string directory)
+ {
+ try
{
- if (sizeInBytes < 1024)
- return $"{sizeInBytes} B";
- else if (sizeInBytes < 1024 * 1024)
- return $"{sizeInBytes / 1024.0:F2} KB";
- else if (sizeInBytes < 1024 * 1024 * 1024)
- return $"{sizeInBytes / (1024.0 * 1024):F2} MB";
- else if (sizeInBytes < 1024L * 1024 * 1024 * 1024)
- return $"{sizeInBytes / (1024.0 * 1024 * 1024):F2} GB";
- else if (sizeInBytes < 1024L * 1024 * 1024 * 1024 * 1024)
- return $"{sizeInBytes / (1024.0 * 1024 * 1024 * 1024):F2} TB";
- else
- return $"{sizeInBytes / (1024.0 * 1024 * 1024 * 1024 * 1024):F2} PB";
+ return Directory.EnumerateDirectories(directory);
+ }
+ catch (UnauthorizedAccessException)
+ {
+ // Skip directories we cannot access
+ return Array.Empty();
+ }
+ catch (IOException)
+ {
+ // Handle IO exceptions for directory operations
+ return Array.Empty();
}
+ }
+
+ private string FormatSize(long sizeInBytes)
+ {
+ return sizeInBytes < 1024
+ ? $"{sizeInBytes} B"
+ : sizeInBytes < 1024 * 1024
+ ? $"{sizeInBytes / 1024.0:F2} KB"
+ : sizeInBytes < 1024 * 1024 * 1024
+ ? $"{sizeInBytes / (1024.0 * 1024):F2} MB"
+ : sizeInBytes < 1024L * 1024 * 1024 * 1024
+ ? $"{sizeInBytes / (1024.0 * 1024 * 1024):F2} GB"
+ : sizeInBytes < 1024L * 1024 * 1024 * 1024 * 1024
+ ? $"{sizeInBytes / (1024.0 * 1024 * 1024 * 1024):F2} TB"
+ : $"{sizeInBytes / (1024.0 * 1024 * 1024 * 1024 * 1024):F2} PB";
+ }
- public List items = new List();
+ public List items = new();
- public string Disk = "";
+ public string Disk = "";
- public DiskWindow(string disk)
+ public DiskWindow(string disk)
+ {
+ Disk = disk;
+ this.InitializeComponent();
+ if (IsAdministrator() == true)
{
- Disk = disk;
- this.InitializeComponent();
- if (IsAdministrator() == true) SysFilesButton.Visibility = Visibility.Collapsed;
- if (disk == "C:")
- {
- items.Add(new CleanItem
- {
- Name = $"Temporary Internet Files",
- ItemPath = $@"{Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData)}\Microsoft\Windows\INetCache",
- ImagePath = "ms-appx:///Assets/imageres_59.ico",
- Size = GetFolderLongSize($@"{Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData)}\Microsoft\Windows\INetCache"),
- DisplaySize = GetFolderSize($@"{Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData)}\Microsoft\Windows\INetCache"),
- Description = "These files are cached copies of web pages, images, and other online media from websites you've visited. They help speed up loading times when you revisit those sites. Deleting these files will free up space but might slow down page loading temporarily until the cache is rebuilt.",
- IsChecked = false,
- });
- }
- if (disk == "C:")
+ SysFilesButton.Visibility = Visibility.Collapsed;
+ }
+
+ if (disk == "C:")
+ {
+ items.Add(new CleanItem
{
- items.Add(new CleanItem
- {
- Name = $"Downloaded Program Files",
- ItemPath = @"C:\Windows\Downloaded Program Files",
- ImagePath = "ms-appx:///Assets/imageres_3.ico",
- Size = GetFolderLongSize(@"C:\Windows\Downloaded Program Files"),
- DisplaySize = GetFolderSize(@"C:\Windows\Downloaded Program Files"),
- Description = "This category includes ActiveX controls and Java applets that were automatically downloaded from the Internet when you view certain web pages. These files are temporarily stored on your computer to speed up the loading of the pages when you revisit them. They can be safely deleted if not needed.",
- IsChecked = true,
- });
- }
- if (disk == "C:")
+ Name = $"Temporary Internet Files",
+ ItemPath = $@"{Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData)}\Microsoft\Windows\INetCache",
+ ImagePath = "ms-appx:///Assets/imageres_59.ico",
+ Size = GetFolderLongSize($@"{Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData)}\Microsoft\Windows\INetCache"),
+ DisplaySize = GetFolderSize($@"{Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData)}\Microsoft\Windows\INetCache"),
+ Description = "These files are cached copies of web pages, images, and other online media from websites you've visited. They help speed up loading times when you revisit those sites. Deleting these files will free up space but might slow down page loading temporarily until the cache is rebuilt.",
+ IsChecked = false,
+ });
+ }
+ if (disk == "C:")
+ {
+ items.Add(new CleanItem
{
- items.Add(new CleanItem
- {
- Name = $"Rebound 11 temporary files",
- ItemPath = @"C:\Rebound11\Temp",
- ImagePath = "ms-appx:///Assets/r11imageres_101.ico",
- Size = GetFolderLongSize(@"C:\Rebound11\Temp"),
- DisplaySize = GetFolderSize(@"C:\Rebound11\Temp"),
- Description = "Rebound 11 might sometimes copy packages and other files to a special temp folder in order for PowerShell to read the paths easier when installing.",
- IsChecked = true,
- });
- }
+ Name = $"Downloaded Program Files",
+ ItemPath = @"C:\Windows\Downloaded Program Files",
+ ImagePath = "ms-appx:///Assets/imageres_3.ico",
+ Size = GetFolderLongSize(@"C:\Windows\Downloaded Program Files"),
+ DisplaySize = GetFolderSize(@"C:\Windows\Downloaded Program Files"),
+ Description = "This category includes ActiveX controls and Java applets that were automatically downloaded from the Internet when you view certain web pages. These files are temporarily stored on your computer to speed up the loading of the pages when you revisit them. They can be safely deleted if not needed.",
+ IsChecked = true,
+ });
+ }
+ if (disk == "C:")
+ {
items.Add(new CleanItem
{
- Name = $"Recycle Bin",
- ItemPath = $@"{disk}\$Recycle.Bin",
- ImagePath = "ms-appx:///Assets/imageres_54.ico",
- Size = GetFolderLongSize($@"{disk}\$Recycle.Bin"),
- DisplaySize = GetFolderSize($@"{disk}\$Recycle.Bin"),
- Description = "The Recycle Bin stores files and folders that you�ve deleted from your computer. These items are not permanently removed until you empty the Recycle Bin. You can recover deleted items from here, but deleting them permanently frees up disk space.",
+ Name = $"Rebound 11 temporary files",
+ ItemPath = @"C:\Rebound11\Temp",
+ ImagePath = "ms-appx:///Assets/r11imageres_101.ico",
+ Size = GetFolderLongSize(@"C:\Rebound11\Temp"),
+ DisplaySize = GetFolderSize(@"C:\Rebound11\Temp"),
+ Description = "Rebound 11 might sometimes copy packages and other files to a special temp folder in order for PowerShell to read the paths easier when installing.",
IsChecked = true,
});
- if (disk == "C:")
+ }
+ items.Add(new CleanItem
+ {
+ Name = $"Recycle Bin",
+ ItemPath = $@"{disk}\$Recycle.Bin",
+ ImagePath = "ms-appx:///Assets/imageres_54.ico",
+ Size = GetFolderLongSize($@"{disk}\$Recycle.Bin"),
+ DisplaySize = GetFolderSize($@"{disk}\$Recycle.Bin"),
+ Description = "The Recycle Bin stores files and folders that you�ve deleted from your computer. These items are not permanently removed until you empty the Recycle Bin. You can recover deleted items from here, but deleting them permanently frees up disk space.",
+ IsChecked = true,
+ });
+ if (disk == "C:")
+ {
+ items.Add(new CleanItem
{
- items.Add(new CleanItem
- {
- Name = $"Temporary Files",
- ItemPath = $@"{Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData)}\Temp",
- ImagePath = "ms-appx:///Assets/imageres_2.ico",
- Size = GetFolderLongSize($@"{Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData)}\Temp"),
- DisplaySize = GetFolderSize($@"{Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData)}\Temp"),
- Description = "These are files created by the operating system and applications inside the AppData folder for temporary use. They are often created during the installation of software or while programs are running. These files can usually be safely deleted once the system or application is done with them.",
- IsChecked = false,
- });
- }
- if (disk == "C:")
+ Name = $"Temporary Files",
+ ItemPath = $@"{Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData)}\Temp",
+ ImagePath = "ms-appx:///Assets/imageres_2.ico",
+ Size = GetFolderLongSize($@"{Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData)}\Temp"),
+ DisplaySize = GetFolderSize($@"{Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData)}\Temp"),
+ Description = "These are files created by the operating system and applications inside the AppData folder for temporary use. They are often created during the installation of software or while programs are running. These files can usually be safely deleted once the system or application is done with them.",
+ IsChecked = false,
+ });
+ }
+ if (disk == "C:")
+ {
+ items.Add(new CleanItem
{
- items.Add(new CleanItem
- {
- Name = $"Thumbnails",
- ItemPath = $@"{Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData)}\Microsoft\Windows\Explorer",
- ImagePath = "ms-appx:///Assets/imageres_2.ico",
- Size = GetFolderLongSizeDB($@"{Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData)}\Microsoft\Windows\Explorer"),
- DisplaySize = GetFolderSizeDB($@"{Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData)}\Microsoft\Windows\Explorer"),
- Description = "Thumbnails are small images used to preview the content of files, such as pictures and videos, within folders. The system caches these images to display them quickly. Deleting thumbnail caches will free up space but will cause the system to regenerate them when needed.",
- IsChecked = false,
- });
- }
- if (disk == "C:")
+ Name = $"Thumbnails",
+ ItemPath = $@"{Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData)}\Microsoft\Windows\Explorer",
+ ImagePath = "ms-appx:///Assets/imageres_2.ico",
+ Size = GetFolderLongSizeDB($@"{Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData)}\Microsoft\Windows\Explorer"),
+ DisplaySize = GetFolderSizeDB($@"{Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData)}\Microsoft\Windows\Explorer"),
+ Description = "Thumbnails are small images used to preview the content of files, such as pictures and videos, within folders. The system caches these images to display them quickly. Deleting thumbnail caches will free up space but will cause the system to regenerate them when needed.",
+ IsChecked = false,
+ });
+ }
+ if (disk == "C:")
+ {
+ items.Add(new CleanItem
{
- items.Add(new CleanItem
- {
- Name = $"System Created Windows Error Reporting",
- ItemPath = $@"C:\ProgramData\Microsoft\Windows\WER",
- ImagePath = "ms-appx:///Assets/EventViewer.png",
- Size = GetFolderLongSize($@"C:\ProgramData\Microsoft\Windows\WER"),
- DisplaySize = GetFolderSize($@"C:\ProgramData\Microsoft\Windows\WER"),
- Description = "These are files generated when your system encounters an error. They contain data that can be used to troubleshoot and diagnose issues with your system. If the reports have been sent to Microsoft or are no longer needed, they can be deleted to free up space.",
- IsChecked = false,
- });
- }
- if (disk == "C:")
+ Name = $"System Created Windows Error Reporting",
+ ItemPath = $@"C:\ProgramData\Microsoft\Windows\WER",
+ ImagePath = "ms-appx:///Assets/EventViewer.png",
+ Size = GetFolderLongSize($@"C:\ProgramData\Microsoft\Windows\WER"),
+ DisplaySize = GetFolderSize($@"C:\ProgramData\Microsoft\Windows\WER"),
+ Description = "These are files generated when your system encounters an error. They contain data that can be used to troubleshoot and diagnose issues with your system. If the reports have been sent to Microsoft or are no longer needed, they can be deleted to free up space.",
+ IsChecked = false,
+ });
+ }
+ if (disk == "C:")
+ {
+ items.Add(new CleanItem
{
- items.Add(new CleanItem
- {
- Name = $"Downloads Folder (Current User)",
- ItemPath = $@"{KnownFolders.GetPath(KnownFolder.Downloads)}",
- ImagePath = "ms-appx:///Assets/imageres_184.ico",
- Size = GetFolderLongSize($@"{KnownFolders.GetPath(KnownFolder.Downloads)}"),
- DisplaySize = GetFolderSize($@"{KnownFolders.GetPath(KnownFolder.Downloads)}"),
- Description = "The current user's downloads folder. When you download a file from the web, it will usually be placed here.",
- IsChecked = true,
- });
- }
- if (disk == "C:" && IsAdministrator() == true)
+ Name = $"Downloads Folder (Current User)",
+ ItemPath = $@"{KnownFolders.GetPath(KnownFolder.Downloads)}",
+ ImagePath = "ms-appx:///Assets/imageres_184.ico",
+ Size = GetFolderLongSize($@"{KnownFolders.GetPath(KnownFolder.Downloads)}"),
+ DisplaySize = GetFolderSize($@"{KnownFolders.GetPath(KnownFolder.Downloads)}"),
+ Description = "The current user's downloads folder. When you download a file from the web, it will usually be placed here.",
+ IsChecked = true,
+ });
+ }
+ if (disk == "C:" && IsAdministrator() == true)
+ {
+ items.Add(new CleanItem
{
- items.Add(new CleanItem
- {
- Name = $"System Cache Files",
- ItemPath = $@"C:\Windows\Prefetch\",
- ImagePath = "ms-appx:///Assets/imageres_2.ico",
- Size = GetFolderLongSize($@"C:\Windows\Prefetch\"),
- DisplaySize = GetFolderSize($@"C:\Windows\Prefetch\"),
- Description = "These include various files used by the system to speed up operations. Examples include prefetch files that help applications start faster and font cache files that speed up font rendering. Deleting these files can reclaim space but might temporarily slow down some operations.",
- IsChecked = false,
- });
- }
- if (disk == "C:" && IsAdministrator() == true)
+ Name = $"System Cache Files",
+ ItemPath = $@"C:\Windows\Prefetch\",
+ ImagePath = "ms-appx:///Assets/imageres_2.ico",
+ Size = GetFolderLongSize($@"C:\Windows\Prefetch\"),
+ DisplaySize = GetFolderSize($@"C:\Windows\Prefetch\"),
+ Description = "These include various files used by the system to speed up operations. Examples include prefetch files that help applications start faster and font cache files that speed up font rendering. Deleting these files can reclaim space but might temporarily slow down some operations.",
+ IsChecked = false,
+ });
+ }
+ if (disk == "C:" && IsAdministrator() == true)
+ {
+ items.Add(new CleanItem
{
- items.Add(new CleanItem
- {
- Name = $"Windows Update Cache Files",
- ItemPath = $@"C:\Windows\SoftwareDistribution",
- ImagePath = "ms-appx:///Assets/imageres_2.ico",
- Size = GetFolderLongSize($@"C:\Windows\SoftwareDistribution"),
- DisplaySize = GetFolderSize($@"C:\Windows\SoftwareDistribution"),
- Description = "Disk Cleanup can remove files that are no longer needed after installing Windows updates. These include old versions of files that have been updated, which can sometimes take up significant disk space. Deleting these files will make it harder to uninstall updates.",
- IsChecked = true,
- });
- }
- if (disk == "C:" && IsAdministrator() == true)
+ Name = $"Windows Update Cache Files",
+ ItemPath = $@"C:\Windows\SoftwareDistribution",
+ ImagePath = "ms-appx:///Assets/imageres_2.ico",
+ Size = GetFolderLongSize($@"C:\Windows\SoftwareDistribution"),
+ DisplaySize = GetFolderSize($@"C:\Windows\SoftwareDistribution"),
+ Description = "Disk Cleanup can remove files that are no longer needed after installing Windows updates. These include old versions of files that have been updated, which can sometimes take up significant disk space. Deleting these files will make it harder to uninstall updates.",
+ IsChecked = true,
+ });
+ }
+ if (disk == "C:" && IsAdministrator() == true)
+ {
+ items.Add(new CleanItem
{
- items.Add(new CleanItem
- {
- Name = $"Previous Windows Installations",
- ItemPath = $@"C:\Windows.old",
- ImagePath = "ms-appx:///Assets/imageres_2.ico",
- Size = GetFolderLongSize($@"C:\Windows.old"),
- DisplaySize = GetFolderSize($@"C:\Windows.old"),
- Description = "If you�ve recently upgraded to a newer version of Windows, files from the previous installation are kept in the Windows.old folder in case you need to revert to the earlier version. Deleting these files will permanently remove the ability to roll back to the previous version.",
- IsChecked = false,
- });
- }
- if (disk == "C:" && IsAdministrator() == true)
+ Name = $"Previous Windows Installations",
+ ItemPath = $@"C:\Windows.old",
+ ImagePath = "ms-appx:///Assets/imageres_2.ico",
+ Size = GetFolderLongSize($@"C:\Windows.old"),
+ DisplaySize = GetFolderSize($@"C:\Windows.old"),
+ Description = "If you�ve recently upgraded to a newer version of Windows, files from the previous installation are kept in the Windows.old folder in case you need to revert to the earlier version. Deleting these files will permanently remove the ability to roll back to the previous version.",
+ IsChecked = false,
+ });
+ }
+ if (disk == "C:" && IsAdministrator() == true)
+ {
+ items.Add(new CleanItem
{
- items.Add(new CleanItem
- {
- Name = $"System Error Memory Dump Files",
- ItemPath = $@"C:\Windows\MEMORY.DMP",
- ImagePath = "ms-appx:///Assets/EventViewer.png",
- Size = GetFolderLongSize($@"C:\Windows\MEMORY.DMP"),
- DisplaySize = GetFolderSize($@"C:\Windows\MEMORY.DMP"),
- Description = "These files are created when Windows crashes and contain a copy of the memory at the time of the crash. They can be used to diagnose the cause of the crash. Large memory dumps can take up significant space and can be safely deleted if no longer needed.",
- IsChecked = false,
- });
- }
- if (disk == "C:" && IsAdministrator() == true)
+ Name = $"System Error Memory Dump Files",
+ ItemPath = $@"C:\Windows\MEMORY.DMP",
+ ImagePath = "ms-appx:///Assets/EventViewer.png",
+ Size = GetFolderLongSize($@"C:\Windows\MEMORY.DMP"),
+ DisplaySize = GetFolderSize($@"C:\Windows\MEMORY.DMP"),
+ Description = "These files are created when Windows crashes and contain a copy of the memory at the time of the crash. They can be used to diagnose the cause of the crash. Large memory dumps can take up significant space and can be safely deleted if no longer needed.",
+ IsChecked = false,
+ });
+ }
+ if (disk == "C:" && IsAdministrator() == true)
+ {
+ items.Add(new CleanItem
{
- items.Add(new CleanItem
- {
- Name = $"System Error Minidump Files",
- ItemPath = $@"C:\Windows\Minidump",
- ImagePath = "ms-appx:///Assets/EventViewer.png",
- Size = GetFolderLongSize($@"C:\Windows\Minidump"),
- DisplaySize = GetFolderSize($@"C:\Windows\Minidump"),
- Description = "Minidumps are smaller versions of memory dump files created when the system crashes. They contain essential information to diagnose the cause of the crash but are smaller in size than full memory dumps. These can be deleted if you no longer need to troubleshoot a crash.",
- IsChecked = false,
- });
- }
- if (disk == "C:" && IsAdministrator() == true)
+ Name = $"System Error Minidump Files",
+ ItemPath = $@"C:\Windows\Minidump",
+ ImagePath = "ms-appx:///Assets/EventViewer.png",
+ Size = GetFolderLongSize($@"C:\Windows\Minidump"),
+ DisplaySize = GetFolderSize($@"C:\Windows\Minidump"),
+ Description = "Minidumps are smaller versions of memory dump files created when the system crashes. They contain essential information to diagnose the cause of the crash but are smaller in size than full memory dumps. These can be deleted if you no longer need to troubleshoot a crash.",
+ IsChecked = false,
+ });
+ }
+ if (disk == "C:" && IsAdministrator() == true)
+ {
+ items.Add(new CleanItem
{
- items.Add(new CleanItem
- {
- Name = $"Temporary Windows Installation Files",
- ItemPath = $@"C:\Windows\Temp",
- ImagePath = "ms-appx:///Assets/imageres_2.ico",
- Size = GetFolderLongSize($@"C:\Windows\Temp"),
- DisplaySize = GetFolderSize($@"C:\Windows\Temp"),
- Description = "These files are created during the installation or updating of Windows. They help ensure the installation process runs smoothly and are typically deleted once the process is complete. Deleting them frees up space without affecting system stability.\r\n",
- IsChecked = false,
- });
- }
- if (disk == "C:" && IsAdministrator() == true)
+ Name = $"Temporary Windows Installation Files",
+ ItemPath = $@"C:\Windows\Temp",
+ ImagePath = "ms-appx:///Assets/imageres_2.ico",
+ Size = GetFolderLongSize($@"C:\Windows\Temp"),
+ DisplaySize = GetFolderSize($@"C:\Windows\Temp"),
+ Description = "These files are created during the installation or updating of Windows. They help ensure the installation process runs smoothly and are typically deleted once the process is complete. Deleting them frees up space without affecting system stability.\r\n",
+ IsChecked = false,
+ });
+ }
+ if (disk == "C:" && IsAdministrator() == true)
+ {
+ items.Add(new CleanItem
{
- items.Add(new CleanItem
- {
- Name = $"Device Driver Packages",
- ItemPath = @"C:\Windows\System32\DriverStore\FileRepository",
- ImagePath = "ms-appx:///Assets/DDORes_2001.ico",
- Size = GetFolderLongSizeDrivers(@"C:\Windows\System32\DriverStore\FileRepository"),
- DisplaySize = GetFolderSizeDrivers(@"C:\Windows\System32\DriverStore\FileRepository"),
- Description = "These are files related to hardware drivers installed on your system. They are used by Windows to manage hardware devices and ensure proper functionality. Over time, old or unused driver packages may accumulate and take up disk space. Cleaning up these packages can help free up storage and keep your system organized. Only outdated or redundant packages will be removed, while active drivers will remain unaffected.",
- IsChecked = false,
- });
- }
+ Name = $"Device Driver Packages",
+ ItemPath = @"C:\Windows\System32\DriverStore\FileRepository",
+ ImagePath = "ms-appx:///Assets/DDORes_2001.ico",
+ Size = GetFolderLongSizeDrivers(@"C:\Windows\System32\DriverStore\FileRepository"),
+ DisplaySize = GetFolderSizeDrivers(@"C:\Windows\System32\DriverStore\FileRepository"),
+ Description = "These are files related to hardware drivers installed on your system. They are used by Windows to manage hardware devices and ensure proper functionality. Over time, old or unused driver packages may accumulate and take up disk space. Cleaning up these packages can help free up storage and keep your system organized. Only outdated or redundant packages will be removed, while active drivers will remain unaffected.",
+ IsChecked = false,
+ });
+ }
- long size = 0;
+ long size = 0;
- foreach (var item in items)
- {
- size += item.Size;
- }
+ foreach (var item in items)
+ {
+ size += item.Size;
+ }
- // Sort the list alphabetically by the Name property
- items.Sort((x, y) => string.Compare(x.Name, y.Name, StringComparison.Ordinal));
- CleanItems.ItemsSource = items;
+ // Sort the list alphabetically by the Name property
+ items.Sort((x, y) => string.Compare(x.Name, y.Name, StringComparison.Ordinal));
+ CleanItems.ItemsSource = items;
- Title.Title = $"You can use Disk Cleanup to free up to {FormatSize(size)} of disk space on ({disk}).";
+ Title.Title = $"You can use Disk Cleanup to free up to {FormatSize(size)} of disk space on ({disk}).";
- CleanItems.SelectedIndex = 0;
+ CleanItems.SelectedIndex = 0;
- CheckItems();
+ CheckItems();
- string commandArgs = string.Join(" ", Environment.GetCommandLineArgs().Skip(1));
+ var commandArgs = string.Join(" ", Environment.GetCommandLineArgs().Skip(1));
- if (commandArgs.Contains("CLEANALL"))
- {
- RunFullOptimization();
- }
+ if (commandArgs.Contains("CLEANALL"))
+ {
+ RunFullOptimization();
}
+ }
- public async void RunFullOptimization()
- {
- SelectAllBox.IsChecked = true;
+ public async void RunFullOptimization()
+ {
+ SelectAllBox.IsChecked = true;
- await Task.Delay(500);
+ await Task.Delay(500);
- CleanItems.IsEnabled = false;
- CleanButton.IsEnabled = false;
- CancelButton.IsEnabled = false;
- SelectAllBox.IsEnabled = false;
- MoreOptions.IsEnabled = false;
- ViewFiles.IsEnabled = false;
- Working.IsIndeterminate = true;
- (this as WindowEx).Title = $"Disk Cleanup : Cleaning drive ({Disk})... (This may take a while)";
+ CleanItems.IsEnabled = false;
+ CleanButton.IsEnabled = false;
+ CancelButton.IsEnabled = false;
+ SelectAllBox.IsEnabled = false;
+ MoreOptions.IsEnabled = false;
+ ViewFiles.IsEnabled = false;
+ Working.IsIndeterminate = true;
+ Title = $"Disk Cleanup : Cleaning drive ({Disk})... (This may take a while)";
- await Task.Delay(100);
+ await Task.Delay(100);
- foreach (var item in items)
+ foreach (var item in items)
+ {
+ if (item.Name == "Thumbnails")
{
- if (item.Name == "Thumbnails")
- {
- DeleteFilesDB(item.ItemPath);
- }
- else if (item.Name == "Device Driver Packages")
- {
- CleanupDriverStore();
- }
- else
- {
- DeleteFiles(item.ItemPath);
- }
+ DeleteFilesDB(item.ItemPath);
}
-
- Close();
- }
-
- public enum KnownFolder
- {
- Contacts,
- Downloads,
- Favorites,
- Links,
- SavedGames,
- SavedSearches
- }
-
- public static class KnownFolders
- {
- private static readonly Dictionary _guids = new()
+ else if (item.Name == "Device Driver Packages")
{
- [KnownFolder.Contacts] = new("56784854-C6CB-462B-8169-88E350ACB882"),
- [KnownFolder.Downloads] = new("374DE290-123F-4565-9164-39C4925E467B"),
- [KnownFolder.Favorites] = new("1777F761-68AD-4D8A-87BD-30B759FA33DD"),
- [KnownFolder.Links] = new("BFB9D5E0-C6A9-404C-B2B2-AE6DB6AF4968"),
- [KnownFolder.SavedGames] = new("4C5C32FF-BB9D-43B0-B5B4-2D72E54EAAA4"),
- [KnownFolder.SavedSearches] = new("7D1D3A04-DEBB-4115-95CF-2F29DA2920DA")
- };
-
- public static string GetPath(KnownFolder knownFolder)
+ CleanupDriverStore();
+ }
+ else
{
- return SHGetKnownFolderPath(_guids[knownFolder], 0);
+ DeleteFiles(item.ItemPath);
}
-
- [DllImport("shell32",
- CharSet = CharSet.Unicode, ExactSpelling = true, PreserveSig = false)]
- private static extern string SHGetKnownFolderPath(
- [MarshalAs(UnmanagedType.LPStruct)] Guid rfid, uint dwFlags,
- nint hToken = 0);
}
- public async void CheckItems()
- {
- try
- {
- await Task.Delay(10);
+ Close();
+ }
- int totalItems = 0;
- int selectedItems = 0;
+ public enum KnownFolder
+ {
+ Contacts,
+ Downloads,
+ Favorites,
+ Links,
+ SavedGames,
+ SavedSearches
+ }
- foreach (var item in items)
- {
- totalItems++;
- if (item.IsChecked == true) selectedItems++;
- }
+ public static class KnownFolders
+ {
+ private static readonly Dictionary _guids = new()
+ {
+ [KnownFolder.Contacts] = new("56784854-C6CB-462B-8169-88E350ACB882"),
+ [KnownFolder.Downloads] = new("374DE290-123F-4565-9164-39C4925E467B"),
+ [KnownFolder.Favorites] = new("1777F761-68AD-4D8A-87BD-30B759FA33DD"),
+ [KnownFolder.Links] = new("BFB9D5E0-C6A9-404C-B2B2-AE6DB6AF4968"),
+ [KnownFolder.SavedGames] = new("4C5C32FF-BB9D-43B0-B5B4-2D72E54EAAA4"),
+ [KnownFolder.SavedSearches] = new("7D1D3A04-DEBB-4115-95CF-2F29DA2920DA")
+ };
+
+ public static string GetPath(KnownFolder knownFolder) => SHGetKnownFolderPath(_guids[knownFolder], 0);
+
+ [DllImport("shell32",
+ CharSet = CharSet.Unicode, ExactSpelling = true, PreserveSig = false)]
+ private static extern string SHGetKnownFolderPath(
+ [MarshalAs(UnmanagedType.LPStruct)] Guid rfid, uint dwFlags,
+ nint hToken = 0);
+ }
- if (CleanItems.SelectedIndex >= 0) ItemDetails.Text = items[CleanItems.SelectedIndex].Description;
+ public async void CheckItems()
+ {
+ try
+ {
+ await Task.Delay(10);
- if (selectedItems == 0)
- {
- SelectAllBox.IsChecked = false;
- }
- else if (selectedItems == totalItems)
- {
- SelectAllBox.IsChecked = true;
- }
- else
+ var totalItems = 0;
+ var selectedItems = 0;
+
+ foreach (var item in items)
+ {
+ totalItems++;
+ if (item.IsChecked == true)
{
- SelectAllBox.IsChecked = null;
+ selectedItems++;
}
-
- CheckItems();
}
- catch
- {
+ if (CleanItems.SelectedIndex >= 0)
+ {
+ ItemDetails.Text = items[CleanItems.SelectedIndex].Description;
}
- }
- private async void MenuFlyoutItem_Click(object sender, RoutedEventArgs e)
+ SelectAllBox.IsChecked = selectedItems == 0 ? false : selectedItems == totalItems ? true : null;
+
+ CheckItems();
+ }
+ catch
{
- string customDefragPath = @"C:\Rebound11\rdfrgui.exe";
- string systemDefragPath = @"C:\Windows\System32\dfrgui.exe";
- try
+ }
+ }
+
+ private async void MenuFlyoutItem_Click(object sender, RoutedEventArgs e)
+ {
+ var customDefragPath = @"C:\Rebound11\rdfrgui.exe";
+
+ try
+ {
+ if (File.Exists(customDefragPath))
{
- if (File.Exists(customDefragPath))
+ // Launch the custom defrag tool
+ _ = Process.Start(new ProcessStartInfo()
{
- // Launch the custom defrag tool
- Process.Start(new ProcessStartInfo()
- {
- FileName = customDefragPath,
- UseShellExecute = true,
- Verb = "runas" // Ensure it runs with admin rights
- });
- }
- else
+ FileName = customDefragPath,
+ UseShellExecute = true,
+ Verb = "runas" // Ensure it runs with admin rights
+ });
+ }
+ else
+ {
+ var startInfo = new ProcessStartInfo
{
- var startInfo = new ProcessStartInfo
- {
- FileName = "powershell.exe",
- UseShellExecute = false,
- CreateNoWindow = true
- };
-
- startInfo.Arguments = $"Start-Process -FilePath \"dfrgui\"";
+ FileName = "powershell.exe",
+ UseShellExecute = false,
+ CreateNoWindow = true,
+ Arguments = $"Start-Process -FilePath \"dfrgui\""
+ };
- try
+ try
+ {
+ var res = Process.Start(startInfo);
+ await res.WaitForExitAsync();
+ if (res.ExitCode == 0)
{
- var res = Process.Start(startInfo);
- await res.WaitForExitAsync();
- if (res.ExitCode == 0) return;
- else throw new Exception();
+ return;
}
- catch (Exception ex)
+ else
{
- await this.ShowMessageDialogAsync($"The system cannot find the file specified or the command line arguments are invalid.", "Error");
+ throw new Exception();
}
}
- }
- catch (Exception ex)
- {
- Debug.WriteLine($"Exception: {ex.Message}");
- ContentDialog noWifiDialog = new ContentDialog
+ catch (Exception)
{
- Title = "Error",
- Content = $"Could not launch Disk Defragmenter: {ex.Message}",
- CloseButtonText = "Ok"
- };
-
- await noWifiDialog.ShowAsync(); // Showing the error dialog
+ await ShowMessageDialogAsync($"The system cannot find the file specified or the command line arguments are invalid.", "Error");
+ }
}
}
-
- private async void MenuFlyoutItem_Click_1(object sender, RoutedEventArgs e)
+ catch (Exception ex)
{
- var startInfo = new ProcessStartInfo
+ Debug.WriteLine($"Exception: {ex.Message}");
+ var noWifiDialog = new ContentDialog
{
- FileName = "powershell.exe",
- UseShellExecute = false,
- CreateNoWindow = true
+ Title = "Error",
+ Content = $"Could not launch Disk Defragmenter: {ex.Message}",
+ CloseButtonText = "Ok"
};
- startInfo.Arguments = $"Start-Process -FilePath \"cleanmgr\"";
+ await noWifiDialog.ShowAsync(); // Showing the error dialog
+ }
+ }
- try
+ private async void MenuFlyoutItem_Click_1(object sender, RoutedEventArgs e)
+ {
+ var startInfo = new ProcessStartInfo
+ {
+ FileName = "powershell.exe",
+ UseShellExecute = false,
+ CreateNoWindow = true,
+ Arguments = $"Start-Process -FilePath \"cleanmgr\""
+ };
+ try
+ {
+ var res = Process.Start(startInfo);
+ await res.WaitForExitAsync();
+ if (res.ExitCode == 0)
{
- var res = Process.Start(startInfo);
- await res.WaitForExitAsync();
- if (res.ExitCode == 0) Close();
- else throw new Exception();
+ Close();
}
- catch (Exception ex)
+ else
{
- await this.ShowMessageDialogAsync($"The system cannot find the file specified or the command line arguments are invalid.", "Error");
+ throw new Exception();
}
}
-
- private async void MenuFlyoutItem_Click_2(object sender, RoutedEventArgs e)
+ catch (Exception)
{
- await Launcher.LaunchUriAsync(new Uri("ms-settings:appsfeatures"));
+ await ShowMessageDialogAsync($"The system cannot find the file specified or the command line arguments are invalid.", "Error");
}
+ }
- private void CleanItems_SelectionChanged(object sender, SelectionChangedEventArgs e)
- {
+ private async void MenuFlyoutItem_Click_2(object sender, RoutedEventArgs e) => await Launcher.LaunchUriAsync(new Uri("ms-settings:appsfeatures"));
- }
+ private void CleanItems_SelectionChanged(object sender, SelectionChangedEventArgs e)
+ {
- private void CheckBox_Click(object sender, RoutedEventArgs e)
+ }
+
+ private void CheckBox_Click(object sender, RoutedEventArgs e)
+ {
+ if (SelectAllBox.IsChecked == true)
{
- if (SelectAllBox.IsChecked == true)
+ CleanItems.ItemsSource = null;
+ foreach (var item in items)
{
- CleanItems.ItemsSource = null;
- foreach (var item in items)
- {
- item.IsChecked = true;
- }
- CleanItems.ItemsSource = items;
- CleanItems.SelectedIndex = 0;
+ item.IsChecked = true;
}
- if (SelectAllBox.IsChecked == false)
+ CleanItems.ItemsSource = items;
+ CleanItems.SelectedIndex = 0;
+ }
+ if (SelectAllBox.IsChecked == false)
+ {
+ CleanItems.ItemsSource = null;
+ foreach (var item in items)
{
- CleanItems.ItemsSource = null;
- foreach (var item in items)
- {
- item.IsChecked = false;
- }
- CleanItems.ItemsSource = items;
- CleanItems.SelectedIndex = 0;
+ item.IsChecked = false;
}
+ CleanItems.ItemsSource = items;
+ CleanItems.SelectedIndex = 0;
}
+ }
- public bool IsAdministrator()
- {
- var identity = WindowsIdentity.GetCurrent();
- var principal = new WindowsPrincipal(identity);
- return principal.IsInRole(WindowsBuiltInRole.Administrator);
- }
+ public bool IsAdministrator()
+ {
+ var identity = WindowsIdentity.GetCurrent();
+ var principal = new WindowsPrincipal(identity);
+ return principal.IsInRole(WindowsBuiltInRole.Administrator);
+ }
- private void CheckBox_Checked(object sender, RoutedEventArgs e)
- {
+ private void CheckBox_Checked(object sender, RoutedEventArgs e)
+ {
- }
+ }
- private void CheckBox_Unchecked(object sender, RoutedEventArgs e)
- {
+ private void CheckBox_Unchecked(object sender, RoutedEventArgs e)
+ {
- }
+ }
- private void Button_Click(object sender, RoutedEventArgs e)
+ private void Button_Click(object sender, RoutedEventArgs e)
+ {
+ _ = Process.Start(new ProcessStartInfo()
{
- Process.Start(new ProcessStartInfo()
- {
- FileName = "powershell.exe",
- UseShellExecute = false,
- CreateNoWindow = true,
- Verb = "runas",
- Arguments = @$"Start-Process ""shell:AppsFolder\e8dfd11c-954d-46a2-b700-9cbc6201f056_pthpn8nb9xcaa!App"" -ArgumentList ""{Disk}"" -Verb RunAs"
- });
- Close();
- }
+ FileName = "powershell.exe",
+ UseShellExecute = false,
+ CreateNoWindow = true,
+ Verb = "runas",
+ Arguments = @$"Start-Process ""shell:AppsFolder\e8dfd11c-954d-46a2-b700-9cbc6201f056_pthpn8nb9xcaa!App"" -ArgumentList ""{Disk}"" -Verb RunAs"
+ });
+ Close();
+ }
- private async void Button_Click_1(object sender, RoutedEventArgs e)
+ private async void Button_Click_1(object sender, RoutedEventArgs e)
+ {
+ CleanItems.IsEnabled = false;
+ CleanButton.IsEnabled = false;
+ CancelButton.IsEnabled = false;
+ SelectAllBox.IsEnabled = false;
+ MoreOptions.IsEnabled = false;
+ ViewFiles.IsEnabled = false;
+ Working.IsIndeterminate = true;
+ Title = $"Disk Cleanup : Cleaning drive ({Disk})... (This may take a while)";
+
+ await Task.Delay(100);
+
+ foreach (var item in items)
{
- CleanItems.IsEnabled = false;
- CleanButton.IsEnabled = false;
- CancelButton.IsEnabled = false;
- SelectAllBox.IsEnabled = false;
- MoreOptions.IsEnabled = false;
- ViewFiles.IsEnabled = false;
- Working.IsIndeterminate = true;
- (this as WindowEx).Title = $"Disk Cleanup : Cleaning drive ({Disk})... (This may take a while)";
-
- await Task.Delay(100);
-
- foreach (var item in items)
+ if (item.IsChecked == true)
{
- if (item.IsChecked == true)
+ if (item.Name == "Thumbnails")
{
- if (item.Name == "Thumbnails")
- {
- DeleteFilesDB(item.ItemPath);
- }
- else if (item.Name == "Device Driver Packages")
- {
- CleanupDriverStore();
- }
- else
- {
- DeleteFiles(item.ItemPath);
- }
+ DeleteFilesDB(item.ItemPath);
+ }
+ else if (item.Name == "Device Driver Packages")
+ {
+ CleanupDriverStore();
+ }
+ else
+ {
+ DeleteFiles(item.ItemPath);
}
}
-
- Close();
}
- private void Button_Click_2(object sender, RoutedEventArgs e)
- {
- Close();
- }
+ Close();
+ }
+
+ private void Button_Click_2(object sender, RoutedEventArgs e) => Close();
- private async void ViewFiles_Click(object sender, RoutedEventArgs e)
+ private async void ViewFiles_Click(object sender, RoutedEventArgs e)
+ {
+ if (items[CleanItems.SelectedIndex].ItemPath.Contains("Recycle.Bin"))
{
- if (items[CleanItems.SelectedIndex].ItemPath.Contains("Recycle.Bin"))
- {
- await Launcher.LaunchFolderPathAsync($"shell:RecycleBinFolder");
- return;
- }
- await Launcher.LaunchFolderPathAsync($"{items[CleanItems.SelectedIndex].ItemPath}");
+ await Launcher.LaunchFolderPathAsync($"shell:RecycleBinFolder");
+ return;
}
+ await Launcher.LaunchFolderPathAsync($"{items[CleanItems.SelectedIndex].ItemPath}");
}
}
diff --git a/Cleanup/MainWindow.xaml.cs b/Cleanup/MainWindow.xaml.cs
index 5a81095..285822c 100644
--- a/Cleanup/MainWindow.xaml.cs
+++ b/Cleanup/MainWindow.xaml.cs
@@ -9,77 +9,73 @@
// To learn more about WinUI, the WinUI project structure,
// and more about our project templates, see: http://aka.ms/winui-project-info.
-namespace Rebound.Cleanup
+namespace Rebound.Cleanup;
+
+///
+/// An empty window that can be used on its own or navigated to within a Frame.
+///
+public sealed partial class MainWindow : WindowEx
{
- ///
- /// An empty window that can be used on its own or navigated to within a Frame.
- ///
- public sealed partial class MainWindow : WindowEx
+ public MainWindow(string disk)
{
- public MainWindow(string disk)
+ this.InitializeComponent();
+ AppWindow.DefaultTitleBarShouldMatchAppModeTheme = true;
+ this.SetWindowSize(375, 235);
+ IsMaximizable = false;
+ IsMinimizable = false;
+ IsResizable = false;
+ this.CenterOnScreen();
+ Title = "Disk Cleanup : Drive Selection";
+ SystemBackdrop = new MicaBackdrop();
+ this.SetIcon($@"{AppContext.BaseDirectory}\Assets\cleanmgr.ico");
+ var x = Directory.GetLogicalDrives();
+ foreach (var i in x)
{
- this.InitializeComponent();
- this.AppWindow.DefaultTitleBarShouldMatchAppModeTheme = true;
- this.SetWindowSize(375, 235);
- this.IsMaximizable = false;
- this.IsMinimizable = false;
- this.IsResizable = false;
- this.CenterOnScreen();
- this.Title = "Disk Cleanup : Drive Selection";
- this.SystemBackdrop = new MicaBackdrop();
- this.SetIcon($@"{AppContext.BaseDirectory}\Assets\cleanmgr.ico");
- var x = Directory.GetLogicalDrives();
- foreach (var i in x)
- {
- DrivesBox.Items.Add(i.Substring(0, 2));
- }
- DrivesBox.SelectedIndex = 0;
+ DrivesBox.Items.Add(i[..2]);
}
+ DrivesBox.SelectedIndex = 0;
+ }
- private async void Button_Click(object sender, RoutedEventArgs e)
- {
- Working.IsIndeterminate = true;
- OkButton.IsEnabled = false;
- CancelButton.IsEnabled = false;
- await Task.Delay(50);
+ private async void Button_Click(object sender, RoutedEventArgs e)
+ {
+ Working.IsIndeterminate = true;
+ OkButton.IsEnabled = false;
+ CancelButton.IsEnabled = false;
+ await Task.Delay(50);
- await OpenWindow(DrivesBox.SelectedItem.ToString());
+ await OpenWindow(DrivesBox.SelectedItem.ToString());
- this.Close();
- }
+ Close();
+ }
- public async Task ArgumentsLaunch(string disk)
- {
- Working.IsIndeterminate = true;
- OkButton.IsEnabled = false;
- CancelButton.IsEnabled = false;
- await Task.Delay(50);
+ public async Task ArgumentsLaunch(string disk)
+ {
+ Working.IsIndeterminate = true;
+ OkButton.IsEnabled = false;
+ CancelButton.IsEnabled = false;
+ await Task.Delay(50);
- await OpenWindow(disk);
+ await OpenWindow(disk);
- this.Close();
- }
-
- public Task OpenWindow(string disk)
- {
- this.Title = "Disk Cleanup : Calculating total cache size... (This may take a while)";
- var win = new DiskWindow(disk);
- win.AppWindow.DefaultTitleBarShouldMatchAppModeTheme = true;
- win.SetWindowSize(450, 640);
- win.IsMaximizable = false;
- win.IsMinimizable = false;
- win.IsResizable = false;
- win.Move(50, 50);
- win.Title = $"Disk Cleanup for ({disk})";
- win.SystemBackdrop = new MicaBackdrop();
- win.SetIcon($@"{AppContext.BaseDirectory}\Assets\cleanmgr.ico");
- win.Show();
- return Task.CompletedTask;
- }
+ Close();
+ }
- private void CancelButton_Click(object sender, RoutedEventArgs e)
- {
- Process.GetCurrentProcess().Kill();
- }
+ public Task OpenWindow(string disk)
+ {
+ Title = "Disk Cleanup : Calculating total cache size... (This may take a while)";
+ var win = new DiskWindow(disk);
+ win.AppWindow.DefaultTitleBarShouldMatchAppModeTheme = true;
+ win.SetWindowSize(450, 640);
+ win.IsMaximizable = false;
+ win.IsMinimizable = false;
+ win.IsResizable = false;
+ win.Move(50, 50);
+ win.Title = $"Disk Cleanup for ({disk})";
+ win.SystemBackdrop = new MicaBackdrop();
+ win.SetIcon($@"{AppContext.BaseDirectory}\Assets\cleanmgr.ico");
+ _ = win.Show();
+ return Task.CompletedTask;
}
+
+ private void CancelButton_Click(object sender, RoutedEventArgs e) => Process.GetCurrentProcess().Kill();
}
diff --git a/Cleanup/Package.appxmanifest b/Cleanup/Package.appxmanifest
index c0bb4a1..1a60fa7 100644
--- a/Cleanup/Package.appxmanifest
+++ b/Cleanup/Package.appxmanifest
@@ -16,7 +16,7 @@
Rebound.Cleanup
- Lenovo
+ Ivirius
Assets\StoreLogo.png
diff --git a/Control/App.xaml.cs b/Control/App.xaml.cs
index 2047110..83b6487 100644
--- a/Control/App.xaml.cs
+++ b/Control/App.xaml.cs
@@ -1,8 +1,6 @@
using System.Diagnostics;
using Microsoft.UI.Xaml;
-#pragma warning disable CA2211 // Non-constant fields should not be visible
-
namespace Rebound.Control;
public partial class App : Application
diff --git a/Control/MainWindow.xaml.cs b/Control/MainWindow.xaml.cs
index 2f29a95..c275283 100644
--- a/Control/MainWindow.xaml.cs
+++ b/Control/MainWindow.xaml.cs
@@ -1,6 +1,5 @@
using System;
using System.Collections.Generic;
-using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using Microsoft.UI.Xaml;
@@ -30,7 +29,7 @@ public MainWindow()
SystemBackdrop = new MicaBackdrop();
Title = "Control Panel";
WindowTitle.Text = Title;
- RootFrame.Navigate(typeof(ModernHomePage));
+ _ = RootFrame.Navigate(typeof(ModernHomePage));
this.CenterOnScreen();
this.SetWindowSize(1250, 750);
@@ -94,7 +93,7 @@ private async void UpButton_Click(object sender, RoutedEventArgs e)
{
case CPL_HOME:
{
- await Launcher.LaunchUriAsync(new Uri(Environment.GetFolderPath(Environment.SpecialFolder.Desktop)));
+ _ = await Launcher.LaunchUriAsync(new Uri(Environment.GetFolderPath(Environment.SpecialFolder.Desktop)));
App.ControlPanelWindow?.Close();
break;
}
@@ -118,7 +117,7 @@ private async void UpButton_Click(object sender, RoutedEventArgs e)
}
default:
{
- await Launcher.LaunchUriAsync(new Uri(Environment.GetFolderPath(Environment.SpecialFolder.Desktop)));
+ _ = await Launcher.LaunchUriAsync(new Uri(Environment.GetFolderPath(Environment.SpecialFolder.Desktop)));
App.ControlPanelWindow?.Close();
break;
}
@@ -133,7 +132,7 @@ private void RefreshButton_Click(object sender, RoutedEventArgs e)
{
newList.Add(item);
}
- RootFrame.Navigate(typeof(HomePage), null, new Microsoft.UI.Xaml.Media.Animation.SuppressNavigationTransitionInfo());
+ _ = RootFrame.Navigate(typeof(HomePage), null, new Microsoft.UI.Xaml.Media.Animation.SuppressNavigationTransitionInfo());
RootFrame.GoBack();
RootFrame.ForwardStack.Clear();
foreach (var item in newList)
@@ -162,10 +161,7 @@ private void MenuFlyoutItem_Click_1(object sender, RoutedEventArgs e)
NavigateToPath();
}
- private void WindowEx_Closed(object sender, WindowEventArgs args)
- {
- App.ControlPanelWindow = null;
- }
+ private void WindowEx_Closed(object sender, WindowEventArgs args) => App.ControlPanelWindow = null;
private void TextBox_LostFocus(object sender, RoutedEventArgs e)
{
@@ -178,7 +174,7 @@ private async void AddressBar_PointerReleased(object sender, PointerRoutedEventA
AddressBar.Visibility = Visibility.Collapsed;
AddressBox.Visibility = Visibility.Visible;
await Task.Delay(10);
- AddressBox.Focus(FocusState.Programmatic);
+ _ = AddressBox.Focus(FocusState.Programmatic);
}
public void HideAll()
@@ -230,14 +226,14 @@ private void AddressBox_KeyUp(object sender, KeyRoutedEventArgs e)
public async void NavigateToPath(bool legacyHomePage = false)
{
HideAll();
- RootFrame.Focus(FocusState.Programmatic);
+ _ = RootFrame.Focus(FocusState.Programmatic);
switch (AddressBox.Text)
{
case CPL_APPEARANCE_AND_PERSONALIZATION:
{
if (RootFrame.Content is not Views.AppearanceAndPersonalization)
{
- App.ControlPanelWindow?.RootFrame.Navigate(typeof(AppearanceAndPersonalization), null, new Microsoft.UI.Xaml.Media.Animation.DrillInNavigationTransitionInfo());
+ _ = (App.ControlPanelWindow?.RootFrame.Navigate(typeof(AppearanceAndPersonalization), null, new Microsoft.UI.Xaml.Media.Animation.DrillInNavigationTransitionInfo()));
}
AppearanceAndPersonalization.Visibility = Visibility.Visible;
return;
@@ -246,7 +242,7 @@ public async void NavigateToPath(bool legacyHomePage = false)
{
if (RootFrame.Content is not Views.SystemAndSecurity)
{
- App.ControlPanelWindow?.RootFrame.Navigate(typeof(SystemAndSecurity), null, new Microsoft.UI.Xaml.Media.Animation.DrillInNavigationTransitionInfo());
+ _ = (App.ControlPanelWindow?.RootFrame.Navigate(typeof(SystemAndSecurity), null, new Microsoft.UI.Xaml.Media.Animation.DrillInNavigationTransitionInfo()));
}
SystemAndSecurity.Visibility = Visibility.Visible;
return;
@@ -255,7 +251,7 @@ public async void NavigateToPath(bool legacyHomePage = false)
{
if (RootFrame.Content is not Views.WindowsTools)
{
- App.ControlPanelWindow?.RootFrame.Navigate(typeof(WindowsTools), null, new Microsoft.UI.Xaml.Media.Animation.DrillInNavigationTransitionInfo());
+ _ = (App.ControlPanelWindow?.RootFrame.Navigate(typeof(WindowsTools), null, new Microsoft.UI.Xaml.Media.Animation.DrillInNavigationTransitionInfo()));
}
SystemAndSecurity.Visibility = Visibility.Visible;
WindowsTools.Visibility = Visibility.Visible;
@@ -265,11 +261,11 @@ public async void NavigateToPath(bool legacyHomePage = false)
{
if (legacyHomePage == false && RootFrame.Content is not ModernHomePage)
{
- App.ControlPanelWindow?.RootFrame.Navigate(typeof(ModernHomePage), null, new Microsoft.UI.Xaml.Media.Animation.DrillInNavigationTransitionInfo());
+ _ = (App.ControlPanelWindow?.RootFrame.Navigate(typeof(ModernHomePage), null, new Microsoft.UI.Xaml.Media.Animation.DrillInNavigationTransitionInfo()));
}
else if (legacyHomePage != false && RootFrame.Content is not HomePage)
{
- App.ControlPanelWindow?.RootFrame.Navigate(typeof(HomePage), null, new Microsoft.UI.Xaml.Media.Animation.DrillInNavigationTransitionInfo());
+ _ = (App.ControlPanelWindow?.RootFrame.Navigate(typeof(HomePage), null, new Microsoft.UI.Xaml.Media.Animation.DrillInNavigationTransitionInfo()));
}
return;
}
@@ -277,7 +273,7 @@ public async void NavigateToPath(bool legacyHomePage = false)
{
try
{
- await Launcher.LaunchUriAsync(new Uri(AddressBox.Text));
+ _ = await Launcher.LaunchUriAsync(new Uri(AddressBox.Text));
Close();
return;
}
@@ -305,7 +301,7 @@ private void MenuFlyoutItem_Click_2(object sender, RoutedEventArgs e)
const int SW_SHOWNORMAL = 1;
// Call ShellExecute to open the File Explorer Options dialog
- ShellExecute(IntPtr.Zero, "open", "control.exe", "/name Microsoft.FolderOptions", null, SW_SHOWNORMAL);
+ _ = ShellExecute(IntPtr.Zero, "open", "control.exe", "/name Microsoft.FolderOptions", null, SW_SHOWNORMAL);
}
private void MenuFlyoutItem_Click_3(object sender, RoutedEventArgs e)
diff --git a/Control/UACWindow.xaml.cs b/Control/UACWindow.xaml.cs
index 96a0571..14cc456 100644
--- a/Control/UACWindow.xaml.cs
+++ b/Control/UACWindow.xaml.cs
@@ -20,15 +20,15 @@ public sealed partial class UACWindow : WindowEx
{
public UACWindow()
{
- this.InitializeComponent();
- this.IsMaximizable = false;
+ InitializeComponent();
+ IsMaximizable = false;
this.SetWindowSize(750, 500);
this.CenterOnScreen();
- this.SystemBackdrop = new MicaBackdrop();
+ SystemBackdrop = new MicaBackdrop();
this.SetIcon($"{AppContext.BaseDirectory}\\Assets\\AppIcons\\imageres_78.ico");
Helpers.Win32.SetDarkMode(this, App.Current);
- this.Title = "User Account Control Settings";
- this.IsResizable = false;
+ Title = "User Account Control Settings";
+ IsResizable = false;
UACConfigurator.UpdateUACSlider(UACSlider);
if (UACSlider.Value == 0)
{
@@ -106,10 +106,7 @@ private void UACSlider_ValueChanged(object sender, RangeBaseValueChangedEventArg
}
}
- private void Button_Click(object sender, RoutedEventArgs e)
- {
- this.Close();
- }
+ private void Button_Click(object sender, RoutedEventArgs e) => Close();
private void Button_Click_1(object sender, RoutedEventArgs e)
{
@@ -150,11 +147,8 @@ private static void SetRegistryValue(string valueName, int value)
{
try
{
- using RegistryKey key = Registry.LocalMachine.CreateSubKey(RegistryKeyPath);
- if (key != null)
- {
- key.SetValue(valueName, value, RegistryValueKind.DWord);
- }
+ using var key = Registry.LocalMachine.CreateSubKey(RegistryKeyPath);
+ key?.SetValue(valueName, value, RegistryValueKind.DWord);
}
catch (Exception ex)
{
@@ -178,13 +172,13 @@ public static void RunPowerShellCommand(string command)
}
};
- process.Start();
+ _ = process.Start();
process.WaitForExit();
}
public static void SetAlwaysNotify()
{
- string command = @"
+ var command = @"
Set-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System' -Name 'EnableLUA' -Value 1;
Set-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System' -Name 'ConsentPromptBehaviorAdmin' -Value 2;
Set-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System' -Name 'PromptOnSecureDesktop' -Value 1;
@@ -194,7 +188,7 @@ public static void SetAlwaysNotify()
public static void SetNotifyWithDim()
{
- string command = @"
+ var command = @"
Set-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System' -Name 'EnableLUA' -Value 1;
Set-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System' -Name 'ConsentPromptBehaviorAdmin' -Value 5;
Set-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System' -Name 'PromptOnSecureDesktop' -Value 1;
@@ -204,7 +198,7 @@ public static void SetNotifyWithDim()
public static void SetNotifyWithoutDim()
{
- string command = @"
+ var command = @"
Set-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System' -Name 'EnableLUA' -Value 1;
Set-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System' -Name 'ConsentPromptBehaviorAdmin' -Value 5;
Set-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System' -Name 'PromptOnSecureDesktop' -Value 0;
@@ -214,7 +208,7 @@ public static void SetNotifyWithoutDim()
public static void SetNeverNotify()
{
- string command = @"
+ var command = @"
Set-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System' -Name 'EnableLUA' -Value 1;
Set-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System' -Name 'ConsentPromptBehaviorAdmin' -Value 0;
Set-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System' -Name 'PromptOnSecureDesktop' -Value 0;
@@ -226,41 +220,39 @@ private static int GetUACState()
{
try
{
- using (RegistryKey key = Registry.LocalMachine.OpenSubKey(RegistryKeyPath))
+ using var key = Registry.LocalMachine.OpenSubKey(RegistryKeyPath);
+ if (key != null)
{
- if (key != null)
- {
- // Read the EnableLUA value
- object enableLUAValue = key.GetValue("EnableLUA");
- object consentPromptBehaviorAdminValue = key.GetValue("ConsentPromptBehaviorAdmin");
- object promptOnSecureDesktopValue = key.GetValue("PromptOnSecureDesktop");
+ // Read the EnableLUA value
+ var enableLUAValue = key.GetValue("EnableLUA");
+ var consentPromptBehaviorAdminValue = key.GetValue("ConsentPromptBehaviorAdmin");
+ var promptOnSecureDesktopValue = key.GetValue("PromptOnSecureDesktop");
- if (enableLUAValue != null)
+ if (enableLUAValue != null)
+ {
+ var enableLUA = Convert.ToInt32(enableLUAValue);
+ if (enableLUA == 1)
{
- int enableLUA = Convert.ToInt32(enableLUAValue);
- if (enableLUA == 1)
- {
- int consentPromptBehaviorAdmin = consentPromptBehaviorAdminValue != null ? Convert.ToInt32(consentPromptBehaviorAdminValue) : -1;
- int promptOnSecureDesktop = promptOnSecureDesktopValue != null ? Convert.ToInt32(promptOnSecureDesktopValue) : -1;
+ var consentPromptBehaviorAdmin = consentPromptBehaviorAdminValue != null ? Convert.ToInt32(consentPromptBehaviorAdminValue) : -1;
+ var promptOnSecureDesktop = promptOnSecureDesktopValue != null ? Convert.ToInt32(promptOnSecureDesktopValue) : -1;
- // Determine the UAC state
- if (consentPromptBehaviorAdmin == 2)
- {
- return 3; // 2: Dim Desktop, 1: No Dim Desktop
- }
- else if (consentPromptBehaviorAdmin == 5)
- {
- return promptOnSecureDesktop == 1 ? 2 : 1; // 2: Dim Desktop, 1: No Dim Desktop
- }
+ // Determine the UAC state
+ if (consentPromptBehaviorAdmin == 2)
+ {
+ return 3; // 2: Dim Desktop, 1: No Dim Desktop
}
- else
+ else if (consentPromptBehaviorAdmin == 5)
{
- return 0; // UAC is disabled (Never Notify)
+ return promptOnSecureDesktop == 1 ? 2 : 1; // 2: Dim Desktop, 1: No Dim Desktop
}
}
+ else
+ {
+ return 0; // UAC is disabled (Never Notify)
+ }
}
- return -1; // Error or UAC setting not found
}
+ return -1; // Error or UAC setting not found
}
catch (Exception ex)
{
@@ -271,26 +263,16 @@ private static int GetUACState()
public static void UpdateUACSlider(Slider uacSlider)
{
- int uacState = GetUACState();
+ var uacState = GetUACState();
// Update the UACSlider based on the UAC state
- switch (uacState)
+ uacSlider.Value = uacState switch
{
- case 0:
- uacSlider.Value = 0; // Never Notify
- break;
- case 1:
- uacSlider.Value = 1; // Notify without Dim Desktop
- break;
- case 2:
- uacSlider.Value = 2; // Notify with Dim Desktop
- break;
- case 3:
- uacSlider.Value = 3; // Always Notify
- break;
- default:
- uacSlider.Value = -1; // Error or Undefined State
- break;
- }
+ 0 => 0,// Never Notify
+ 1 => 1,// Notify without Dim Desktop
+ 2 => 2,// Notify with Dim Desktop
+ 3 => 3,// Always Notify
+ _ => (double)-1,// Error or Undefined State
+ };
}
}
diff --git a/Control/ViewModels/SystemAndSecurityModel.cs b/Control/ViewModels/SystemAndSecurityModel.cs
index bb05bbf..5031bfb 100644
--- a/Control/ViewModels/SystemAndSecurityModel.cs
+++ b/Control/ViewModels/SystemAndSecurityModel.cs
@@ -10,7 +10,6 @@
using Windows.System;
#pragma warning disable CS1998 // Async method lacks 'await' operators and will run synchronously
-#pragma warning disable SYSLIB1054 // Use 'LibraryImportAttribute' instead of 'DllImportAttribute' to generate P/Invoke marshalling code at compile time
namespace Rebound.Control.ViewModels;
@@ -111,7 +110,7 @@ public static async Task CheckDefenderStatus(StackPanel SecurityBars)
{
var sev = InfoBarSeverity.Informational;
var msg = string.Empty;
- var e = await DecodeProductState((int)((uint)queryObj["productState"]));
+ var e = await DecodeProductState((int)(uint)queryObj["productState"]);
switch (e[..1])
{
@@ -183,7 +182,7 @@ public static async Task CheckDefenderStatus(StackPanel SecurityBars)
Content = "Open",
Margin = new Thickness(0, 0, 0, 15)
};
- y.Click += async (s, e) => { await Launcher.LaunchUriAsync(new Uri("windowsdefender://")); };
+ y.Click += async (s, e) => { _ = await Launcher.LaunchUriAsync(new Uri("windowsdefender://")); };
x.Content = y;
}
if (sev is InfoBarSeverity.Success or InfoBarSeverity.Informational)
diff --git a/Control/Views/AppearanceAndPersonalization.xaml.cs b/Control/Views/AppearanceAndPersonalization.xaml.cs
index b88a028..3ad8f13 100644
--- a/Control/Views/AppearanceAndPersonalization.xaml.cs
+++ b/Control/Views/AppearanceAndPersonalization.xaml.cs
@@ -6,8 +6,6 @@
using Microsoft.UI.Xaml.Controls;
using Windows.System;
-#pragma warning disable SYSLIB1054 // Use 'LibraryImportAttribute' instead of 'DllImportAttribute' to generate P/Invoke marshalling code at compile time
-
namespace Rebound.Control.Views;
public sealed partial class AppearanceAndPersonalization : Page
@@ -36,7 +34,7 @@ private async void ApplyThemeClick(object sender, RoutedEventArgs e)
_ = PleaseWaitDialog.ShowAsync();
App.ControlPanelWindow.IsAlwaysOnTop = true;
var filePath = $"{AppContext.BaseDirectory}\\Themes\\{((FrameworkElement)sender).Tag}.deskthemepack";
- Process.Start(new ProcessStartInfo()
+ _ = Process.Start(new ProcessStartInfo()
{
FileName = $"{filePath}",
UseShellExecute = true
@@ -50,7 +48,7 @@ private async void ApplyThemeClick(object sender, RoutedEventArgs e)
Process.GetProcessesByName("SystemSettings")[0].Kill();
}
await Task.Delay(200);
- App.ControlPanelWindow.BringToFront();
+ _ = App.ControlPanelWindow.BringToFront();
PleaseWaitDialog.Hide();
}
@@ -60,7 +58,7 @@ private static void OpenFileExplorerOptions()
const int SW_SHOWNORMAL = 1;
// Call ShellExecute to open the File Explorer Options dialog
- ShellExecute(IntPtr.Zero, "open", "control.exe", "/name Microsoft.FolderOptions", null, SW_SHOWNORMAL);
+ _ = ShellExecute(IntPtr.Zero, "open", "control.exe", "/name Microsoft.FolderOptions", null, SW_SHOWNORMAL);
}
[DllImport("shell32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
@@ -70,11 +68,11 @@ private async void NavigationView_SelectionChanged(NavigationView sender, Naviga
{
if ((NavigationViewItem)sender.SelectedItem == TBAndNav)
{
- await Launcher.LaunchUriAsync(new Uri("ms-settings:taskbar"));
+ _ = await Launcher.LaunchUriAsync(new Uri("ms-settings:taskbar"));
}
if ((NavigationViewItem)sender.SelectedItem == Access)
{
- await Launcher.LaunchUriAsync(new Uri("ms-settings:easeofaccess"));
+ _ = await Launcher.LaunchUriAsync(new Uri("ms-settings:easeofaccess"));
}
if ((NavigationViewItem)sender.SelectedItem == ExpOptions)
{
@@ -82,7 +80,7 @@ private async void NavigationView_SelectionChanged(NavigationView sender, Naviga
}
if ((NavigationViewItem)sender.SelectedItem == Fonts)
{
- await Launcher.LaunchUriAsync(new Uri("ms-settings:fonts"));
+ _ = await Launcher.LaunchUriAsync(new Uri("ms-settings:fonts"));
}
sender.SelectedItem = Rebound11Item;
}
diff --git a/Control/Views/HomePage.xaml.cs b/Control/Views/HomePage.xaml.cs
index c6d04c1..a848862 100644
--- a/Control/Views/HomePage.xaml.cs
+++ b/Control/Views/HomePage.xaml.cs
@@ -9,111 +9,85 @@
// To learn more about WinUI, the WinUI project structure,
// and more about our project templates, see: http://aka.ms/winui-project-info.
-namespace Rebound.Control.Views
+namespace Rebound.Control.Views;
+
+///
+/// An empty page that can be used on its own or navigated to within a Frame.
+///
+public sealed partial class HomePage : Page
{
- ///
- /// An empty page that can be used on its own or navigated to within a Frame.
- ///
- public sealed partial class HomePage : Page
+ public HomePage()
{
- public HomePage()
+ InitializeComponent();
+ App.ControlPanelWindow?.TitleBarEx.SetWindowIcon("Assets\\AppIcons\\rcontrol.ico");
+ if (App.ControlPanelWindow != null)
{
- this.InitializeComponent();
- if (App.ControlPanelWindow != null) App.ControlPanelWindow.TitleBarEx.SetWindowIcon("Assets\\AppIcons\\rcontrol.ico");
- if (App.ControlPanelWindow != null) App.ControlPanelWindow.Title = "Rebound Control Panel";
+ App.ControlPanelWindow.Title = "Rebound Control Panel";
}
+ }
- private void BackButton_Click(object sender, RoutedEventArgs e)
- {
- if (App.ControlPanelWindow != null)
- {
- App.ControlPanelWindow.RootFrame.GoBack();
- }
- }
+ private void BackButton_Click(object sender, RoutedEventArgs e) => App.ControlPanelWindow?.RootFrame.GoBack();
- private void ForwardButton_Click(object sender, RoutedEventArgs e)
- {
- if (App.ControlPanelWindow != null)
- {
- App.ControlPanelWindow.RootFrame.GoForward();
- }
- }
+ private void ForwardButton_Click(object sender, RoutedEventArgs e) => App.ControlPanelWindow?.RootFrame.GoForward();
- private async void UpButton_Click(object sender, RoutedEventArgs e)
- {
- await Launcher.LaunchUriAsync(new Uri(Environment.GetFolderPath(Environment.SpecialFolder.Desktop)));
- App.ControlPanelWindow.Close();
- }
+ private async void UpButton_Click(object sender, RoutedEventArgs e)
+ {
+ _ = await Launcher.LaunchUriAsync(new Uri(Environment.GetFolderPath(Environment.SpecialFolder.Desktop)));
+ App.ControlPanelWindow.Close();
+ }
- private void RefreshButton_Click(object sender, RoutedEventArgs e)
+ private void RefreshButton_Click(object sender, RoutedEventArgs e)
+ {
+ if (App.ControlPanelWindow != null)
{
- if (App.ControlPanelWindow != null)
+ var oldHistory = App.ControlPanelWindow.RootFrame.ForwardStack;
+ var newList = new List();
+ foreach (var item in oldHistory)
{
- var oldHistory = App.ControlPanelWindow.RootFrame.ForwardStack;
- var newList = new List();
- foreach (var item in oldHistory)
- {
- newList.Add(item);
- }
- App.ControlPanelWindow.RootFrame.Navigate(typeof(HomePage), null, new Microsoft.UI.Xaml.Media.Animation.SuppressNavigationTransitionInfo());
- App.ControlPanelWindow.RootFrame.GoBack();
- App.ControlPanelWindow.RootFrame.ForwardStack.Clear();
- foreach (var item in newList)
- {
- App.ControlPanelWindow.RootFrame.ForwardStack.Add(item);
- }
+ newList.Add(item);
}
- }
-
- private void Button_Click(object sender, RoutedEventArgs e)
- {
- if (App.ControlPanelWindow != null)
+ _ = App.ControlPanelWindow.RootFrame.Navigate(typeof(HomePage), null, new Microsoft.UI.Xaml.Media.Animation.SuppressNavigationTransitionInfo());
+ App.ControlPanelWindow.RootFrame.GoBack();
+ App.ControlPanelWindow.RootFrame.ForwardStack.Clear();
+ foreach (var item in newList)
{
- App.ControlPanelWindow.RootFrame.Navigate(typeof(HomePage), null, new Microsoft.UI.Xaml.Media.Animation.DrillInNavigationTransitionInfo());
+ App.ControlPanelWindow.RootFrame.ForwardStack.Add(item);
}
}
+ }
- private void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
- {
- if ((sender as ComboBox).SelectedIndex == 0 && (App.ControlPanelWindow != null))
- {
- App.ControlPanelWindow.RootFrame.Navigate(typeof(HomePage), null, new Microsoft.UI.Xaml.Media.Animation.DrillInNavigationTransitionInfo());
- }
- if ((sender as ComboBox).SelectedIndex == 1 && (App.ControlPanelWindow != null))
- {
- App.ControlPanelWindow.RootFrame.Navigate(typeof(ModernHomePage), null, new Microsoft.UI.Xaml.Media.Animation.DrillInNavigationTransitionInfo());
- }
- }
+ private void Button_Click(object sender, RoutedEventArgs e) => App.ControlPanelWindow?.RootFrame.Navigate(typeof(HomePage), null, new Microsoft.UI.Xaml.Media.Animation.DrillInNavigationTransitionInfo());
- private void HyperlinkButton_Click(object sender, RoutedEventArgs e)
+ private void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
+ {
+ if ((sender as ComboBox).SelectedIndex == 0 && (App.ControlPanelWindow != null))
{
- var info = new ProcessStartInfo()
- {
- FileName = "powershell.exe",
- Arguments = "Start-Process -FilePath \"C:\\Windows\\System32\\control.exe\"",
- Verb = "runas",
- UseShellExecute = false,
- CreateNoWindow = true
- };
-
- var process = Process.Start(info);
-
- App.ControlPanelWindow.Close();
+ _ = App.ControlPanelWindow.RootFrame.Navigate(typeof(HomePage), null, new Microsoft.UI.Xaml.Media.Animation.DrillInNavigationTransitionInfo());
}
-
- private void MenuFlyoutItem_Click(object sender, RoutedEventArgs e)
+ if ((sender as ComboBox).SelectedIndex == 1 && (App.ControlPanelWindow != null))
{
- App.ControlPanelWindow.RootFrame.Navigate(typeof(AppearanceAndPersonalization), null, new Microsoft.UI.Xaml.Media.Animation.DrillInNavigationTransitionInfo());
+ _ = App.ControlPanelWindow.RootFrame.Navigate(typeof(ModernHomePage), null, new Microsoft.UI.Xaml.Media.Animation.DrillInNavigationTransitionInfo());
}
+ }
- private void Button_Click_1(object sender, RoutedEventArgs e)
+ private void HyperlinkButton_Click(object sender, RoutedEventArgs e)
+ {
+ var info = new ProcessStartInfo()
{
- App.ControlPanelWindow.RootFrame.Navigate(typeof(AppearanceAndPersonalization), null, new Microsoft.UI.Xaml.Media.Animation.DrillInNavigationTransitionInfo());
- }
+ FileName = "powershell.exe",
+ Arguments = "Start-Process -FilePath \"C:\\Windows\\System32\\control.exe\"",
+ Verb = "runas",
+ UseShellExecute = false,
+ CreateNoWindow = true
+ };
+ _ = Process.Start(info);
- private void MenuFlyoutItem_Click_1(object sender, RoutedEventArgs e)
- {
- App.ControlPanelWindow.RootFrame.Navigate(typeof(SystemAndSecurity), null, new Microsoft.UI.Xaml.Media.Animation.DrillInNavigationTransitionInfo());
- }
+ App.ControlPanelWindow.Close();
}
+
+ private void MenuFlyoutItem_Click(object sender, RoutedEventArgs e) => App.ControlPanelWindow.RootFrame.Navigate(typeof(AppearanceAndPersonalization), null, new Microsoft.UI.Xaml.Media.Animation.DrillInNavigationTransitionInfo());
+
+ private void Button_Click_1(object sender, RoutedEventArgs e) => App.ControlPanelWindow.RootFrame.Navigate(typeof(AppearanceAndPersonalization), null, new Microsoft.UI.Xaml.Media.Animation.DrillInNavigationTransitionInfo());
+
+ private void MenuFlyoutItem_Click_1(object sender, RoutedEventArgs e) => App.ControlPanelWindow.RootFrame.Navigate(typeof(SystemAndSecurity), null, new Microsoft.UI.Xaml.Media.Animation.DrillInNavigationTransitionInfo());
}
diff --git a/Control/Views/ModernHomePage.xaml.cs b/Control/Views/ModernHomePage.xaml.cs
index 1800df2..491877a 100644
--- a/Control/Views/ModernHomePage.xaml.cs
+++ b/Control/Views/ModernHomePage.xaml.cs
@@ -19,9 +19,13 @@ public sealed partial class ModernHomePage : Page
{
public ModernHomePage()
{
- this.InitializeComponent();
- if (App.ControlPanelWindow != null) App.ControlPanelWindow.TitleBarEx.SetWindowIcon("AppRT\\Products\\Associated\\rcontrol.ico");
- if (App.ControlPanelWindow != null) App.ControlPanelWindow.Title = "Control Panel";
+ InitializeComponent();
+ App.ControlPanelWindow?.TitleBarEx.SetWindowIcon("AppRT\\Products\\Associated\\rcontrol.ico");
+ if (App.ControlPanelWindow != null)
+ {
+ App.ControlPanelWindow.Title = "Control Panel";
+ }
+
LoadWallpaper();
DisplaySystemInformation();
}
@@ -29,16 +33,16 @@ public ModernHomePage()
private void DisplaySystemInformation()
{
// Get Current User
- string currentUser = Environment.UserName;
+ var currentUser = Environment.UserName;
// Get PC Name
- string pcName = Environment.MachineName;
+ var pcName = Environment.MachineName;
// Get CPU Name
- string cpuName = GetCPUName();
+ var cpuName = GetCPUName();
// Get RAM Capacity
- string ramCapacity = GetRAMCapacity();
+ var ramCapacity = GetRAMCapacity();
// Displaying the information (Assuming you have TextBlocks in your XAML)
CurrentUser.Text = $"Logged in as {currentUser}";
@@ -49,7 +53,7 @@ private void DisplaySystemInformation()
private string GetCPUName()
{
- string cpuName = string.Empty;
+ var cpuName = string.Empty;
using (var searcher = new ManagementObjectSearcher("select Name from Win32_Processor"))
{
foreach (var item in searcher.Get())
@@ -85,8 +89,8 @@ private string GetRAMCapacity()
// Method to retrieve the current user's wallpaper path
private string GetWallpaperPath()
{
- StringBuilder wallpaperPath = new StringBuilder(MAX_PATH);
- SystemParametersInfo(SPI_GETDESKWALLPAPER, MAX_PATH, wallpaperPath, 0);
+ var wallpaperPath = new StringBuilder(MAX_PATH);
+ _ = SystemParametersInfo(SPI_GETDESKWALLPAPER, MAX_PATH, wallpaperPath, 0);
return wallpaperPath.ToString();
}
@@ -132,19 +136,19 @@ private async void NavigationView_SelectionChanged(NavigationView sender, Naviga
}
else if ((string)((NavigationViewItem)sender.SelectedItem).Tag is "Programs" or "Uninstall a program")
{
- await Launcher.LaunchUriAsync(new Uri("ms-settings:appsfeatures"));
+ _ = await Launcher.LaunchUriAsync(new Uri("ms-settings:appsfeatures"));
}
}
catch (Exception ex)
{
- if (App.ControlPanelWindow != null) App.ControlPanelWindow.Title = ex.Message;
+ if (App.ControlPanelWindow != null)
+ {
+ App.ControlPanelWindow.Title = ex.Message;
+ }
}
}
- private void MenuFlyoutItem_Click(object sender, RoutedEventArgs e)
- {
- App.ControlPanelWindow.RootFrame.Navigate(typeof(AppearanceAndPersonalization), null, new Microsoft.UI.Xaml.Media.Animation.DrillInNavigationTransitionInfo());
- }
+ private void MenuFlyoutItem_Click(object sender, RoutedEventArgs e) => App.ControlPanelWindow.RootFrame.Navigate(typeof(AppearanceAndPersonalization), null, new Microsoft.UI.Xaml.Media.Animation.DrillInNavigationTransitionInfo());
private void SettingsCard_Click(object sender, RoutedEventArgs e)
{
@@ -156,20 +160,16 @@ private void SettingsCard_Click(object sender, RoutedEventArgs e)
UseShellExecute = false,
CreateNoWindow = true
};
-
- var process = Process.Start(info);
+ _ = Process.Start(info);
App.ControlPanelWindow.Close();
}
- private void MenuFlyoutItem_Click_1(object sender, RoutedEventArgs e)
- {
- App.ControlPanelWindow.RootFrame.Navigate(typeof(SystemAndSecurity), null, new Microsoft.UI.Xaml.Media.Animation.DrillInNavigationTransitionInfo());
- }
+ private void MenuFlyoutItem_Click_1(object sender, RoutedEventArgs e) => App.ControlPanelWindow.RootFrame.Navigate(typeof(SystemAndSecurity), null, new Microsoft.UI.Xaml.Media.Animation.DrillInNavigationTransitionInfo());
private void ReboundHubSettingsCard_Click(object sender, RoutedEventArgs e)
{
- Process.Start(new ProcessStartInfo("rebound:") { UseShellExecute = true });
+ _ = Process.Start(new ProcessStartInfo("rebound:") { UseShellExecute = true });
App.ControlPanelWindow.Close();
}
}
diff --git a/Control/Views/SystemAndSecurity.xaml.cs b/Control/Views/SystemAndSecurity.xaml.cs
index 670bb6c..4b31b28 100644
--- a/Control/Views/SystemAndSecurity.xaml.cs
+++ b/Control/Views/SystemAndSecurity.xaml.cs
@@ -1,8 +1,6 @@
using System;
using System.Diagnostics;
-using System.IO;
using System.Threading.Tasks;
-using IWshRuntimeLibrary;
using Microsoft.UI.Xaml;
using Microsoft.UI.Xaml.Controls;
using Rebound.Control.ViewModels;
@@ -39,11 +37,11 @@ public async Task UpdateSecurityInformation()
var driveEncrypted = await SystemAndSecurityModel.IsDriveEncrypted("C");
var isPasswordComplex = await SystemAndSecurityModel.IsPasswordComplex();
var securityIndex =
- uac * 1 + // 10% of total
- (defenderStatus == true ? 1 : 0) * 5 + // 50% of total
- (updatesPending == false ? 1 : 0) * 2.5 + // 25% of total
- (driveEncrypted == true ? 1 : 0) * 1 + // 10% of total
- (isPasswordComplex == true ? 1 : 0) * 0.5; // 5% of total
+ (uac * 1) + // 10% of total
+ ((defenderStatus == true ? 1 : 0) * 5) + // 50% of total
+ ((updatesPending == false ? 1 : 0) * 2.5) + // 25% of total
+ ((driveEncrypted == true ? 1 : 0) * 1) + // 10% of total
+ ((isPasswordComplex == true ? 1 : 0) * 0.5); // 5% of total
string status;
InfoBarSeverity sev2;
@@ -130,12 +128,12 @@ private void NavigationView_SelectionChanged(NavigationView sender, NavigationVi
private void SettingsCard_Click_1(object sender, RoutedEventArgs e)
{
var win = new UACWindow();
- win.Show();
+ _ = win.Show();
}
private async void Button_Click_1(object sender, RoutedEventArgs e)
{
- var destDir = $@"{Environment.GetFolderPath(Environment.SpecialFolder.StartMenu)}\Programs\Rebound 11 Tools";
+ _ = $@"{Environment.GetFolderPath(Environment.SpecialFolder.StartMenu)}\Programs\Rebound 11 Tools";
// PowerShell command to create the folder
var powerShellCommand = @"
@@ -162,14 +160,14 @@ private async void Button_Click_1(object sender, RoutedEventArgs e)
using (var process = new Process())
{
process.StartInfo = startInfo;
- process.Start();
+ _ = process.Start();
// Capture the output
var output = process.StandardOutput.ReadToEnd();
process.WaitForExit();
}
- await InstallExeWithShortcut(
+ _ = await InstallExeWithShortcut(
"Rebound 11 Quick Full Computer Cleanup",
$"{AppContext.BaseDirectory}\\Reserved\\QuickFullComputerCleanup.exe",
@"C:\Rebound11\QuickFullComputerCleanup.exe",
@@ -225,14 +223,11 @@ private void Button_Click_3(object sender, RoutedEventArgs e)
{
if (File.Exists(@"C:\Rebound11\QuickFullComputerCleanup.exe"))
{
- Process.Start(@"C:\Rebound11\QuickFullComputerCleanup.exe");
+ _ = Process.Start(@"C:\Rebound11\QuickFullComputerCleanup.exe");
}
}
- private void Expander_Expanding(Expander sender, ExpanderExpandingEventArgs args)
- {
- GetCurrentSecurityIndex();
- }
+ private void Expander_Expanding(Expander sender, ExpanderExpandingEventArgs args) => GetCurrentSecurityIndex();
public async Task InstallExeWithShortcut(string displayAppName, string exeFile, string exeDestination, string lnkFile, string lnkDestination, string exeDisplayName, string lnkDisplayName)
{
diff --git a/Control/Views/WindowsTools.xaml.cs b/Control/Views/WindowsTools.xaml.cs
index 731e5e9..618790c 100644
--- a/Control/Views/WindowsTools.xaml.cs
+++ b/Control/Views/WindowsTools.xaml.cs
@@ -13,7 +13,7 @@ public sealed partial class WindowsTools : Page
{
public class ProgramItem()
{
- public string Name
+ public required string Name
{
get; set;
}
@@ -25,15 +25,15 @@ public Visibility TagVisibility
{
get; set;
}
- public string SpecialTag
+ public required string SpecialTag
{
get; set;
}
- public string Path
+ public required string Path
{
get; set;
}
- public string Icon
+ public required string Icon
{
get; set;
}
@@ -43,8 +43,8 @@ public bool IsEnabled
}
}
- public List items = new()
- {
+ public List items =
+ [
new ProgramItem()
{
Icon = "ms-appx:///AppRT/Exported/imageres_15.png",
@@ -155,11 +155,11 @@ public bool IsEnabled
AdminVisibility = Visibility.Collapsed,
SpecialTag = "SYSTEM",
},
- };
+ ];
public WindowsTools()
{
- this.InitializeComponent();
+ InitializeComponent();
App.ControlPanelWindow?.TitleBarEx.SetWindowIcon("AppRT\\Exported\\imageres_114.ico");
if (App.ControlPanelWindow is not null)
{
diff --git a/Defrag/App.xaml.cs b/Defrag/App.xaml.cs
index 45843b1..c83df8e 100644
--- a/Defrag/App.xaml.cs
+++ b/Defrag/App.xaml.cs
@@ -20,10 +20,7 @@ public App()
_singleInstanceApp.Launched += OnSingleInstanceLaunched;
}
- protected override void OnLaunched(LaunchActivatedEventArgs args)
- {
- _singleInstanceApp?.Launch(args.Arguments);
- }
+ protected override void OnLaunched(LaunchActivatedEventArgs args) => _singleInstanceApp?.Launch(args.Arguments);
private async void OnSingleInstanceLaunched(object? sender, SingleInstanceLaunchEventArgs e)
{
diff --git a/Defrag/Helpers/DefragHelper.cs b/Defrag/Helpers/DefragHelper.cs
index 59d8321..d2c72fc 100644
--- a/Defrag/Helpers/DefragHelper.cs
+++ b/Defrag/Helpers/DefragHelper.cs
@@ -42,24 +42,11 @@ public static List GetSystemVolumes()
var size = (ulong)volume["Capacity"];
// We can further refine this by querying for EFI, Recovery, etc., based on size and file system
- string friendlyName;
- if (fileSystem == "FAT32" && size < 512 * 1024 * 1024)
- {
- friendlyName = "EFI System Partition";
- }
- else if (fileSystem == "NTFS" && size > 500 * 1024 * 1024)
- {
- friendlyName = "Recovery Partition";
- }
- else if (fileSystem == "NTFS" && size < 500 * 1024 * 1024)
- {
- friendlyName = "System Reserved Partition";
- }
- else
- {
- friendlyName = "Unknown System Partition";
- }
-
+ var friendlyName = fileSystem == "FAT32" && size < 512 * 1024 * 1024
+ ? "EFI System Partition"
+ : fileSystem == "NTFS" && size > 500 * 1024 * 1024
+ ? "Recovery Partition"
+ : fileSystem == "NTFS" && size < 500 * 1024 * 1024 ? "System Reserved Partition" : "Unknown System Partition";
volumes.Add(new VolumeInfo
{
GUID = volumePath,
diff --git a/Defrag/Helpers/Win32Helper.cs b/Defrag/Helpers/Win32Helper.cs
index 8242fa1..bd640d0 100644
--- a/Defrag/Helpers/Win32Helper.cs
+++ b/Defrag/Helpers/Win32Helper.cs
@@ -7,8 +7,6 @@
using WinUIEx.Messaging;
#nullable enable
-#pragma warning disable SYSLIB1054 // Use 'LibraryImportAttribute' instead of 'DllImportAttribute' to generate P/Invoke marshalling code at compile time
-#pragma warning disable CA1401 // P/Invokes should not be visible
namespace Rebound.Defrag.Helpers;
@@ -49,7 +47,7 @@ public enum DriveType : uint
public static void RemoveIcon(WindowEx window)
{
var hWnd = WinRT.Interop.WindowNative.GetWindowHandle(window);
- SetWindowLongPtr(hWnd, -20, 0x00000001L);
+ _ = SetWindowLongPtr(hWnd, -20, 0x00000001L);
}
[DllImport("user32.dll", SetLastError = true)]
@@ -92,16 +90,9 @@ async void CheckTheme()
[DllImport("User32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
private static extern bool EnableWindow(IntPtr hWnd, bool bEnable);
- private const int GWL_HWNDPARENT = (-8);
+ private const int GWL_HWNDPARENT = -8;
- private static IntPtr SetWindowLong(IntPtr hWnd, int nIndex, IntPtr dwNewLong)
- {
- if (IntPtr.Size == 4)
- {
- return SetWindowLongPtr32(hWnd, nIndex, dwNewLong);
- }
- return SetWindowLongPtr64(hWnd, nIndex, dwNewLong);
- }
+ private static IntPtr SetWindowLong(IntPtr hWnd, int nIndex, IntPtr dwNewLong) => IntPtr.Size == 4 ? SetWindowLongPtr32(hWnd, nIndex, dwNewLong) : SetWindowLongPtr64(hWnd, nIndex, dwNewLong);
[DllImport("User32.dll", CharSet = CharSet.Auto, EntryPoint = "SetWindowLong")]
private static extern IntPtr SetWindowLongPtr32(IntPtr hWnd, int nIndex, IntPtr dwNewLong);
@@ -113,20 +104,20 @@ public static void CreateModalWindow(WindowEx parentWindow, WindowEx childWindow
{
var hWndChildWindow = WinRT.Interop.WindowNative.GetWindowHandle(childWindow);
var hWndParentWindow = WinRT.Interop.WindowNative.GetWindowHandle(parentWindow);
- SetWindowLong(hWndChildWindow, GWL_HWNDPARENT, hWndParentWindow);
+ _ = SetWindowLong(hWndChildWindow, GWL_HWNDPARENT, hWndParentWindow);
((OverlappedPresenter)childWindow.AppWindow.Presenter).IsModal = true;
if (blockInput == true)
{
- EnableWindow(hWndParentWindow, false);
+ _ = EnableWindow(hWndParentWindow, false);
childWindow.Closed += ChildWindow_Closed;
void ChildWindow_Closed(object sender, Microsoft.UI.Xaml.WindowEventArgs args)
{
- EnableWindow(hWndParentWindow, true);
+ _ = EnableWindow(hWndParentWindow, true);
}
}
if (summonWindowAutomatically == true)
{
- childWindow.Show();
+ _ = childWindow.Show();
}
WindowMessageMonitor _msgMonitor;
diff --git a/Defrag/MainWindow.xaml.cs b/Defrag/MainWindow.xaml.cs
index 31f7126..0465f54 100644
--- a/Defrag/MainWindow.xaml.cs
+++ b/Defrag/MainWindow.xaml.cs
@@ -14,16 +14,11 @@
using Microsoft.Win32.TaskScheduler;
using Microsoft.WindowsAPICodePack.Taskbar;
using Rebound.Defrag.Helpers;
-using Windows.ApplicationModel;
-using Windows.ApplicationModel.Core;
-using Windows.Storage;
-using Windows.System;
using WinUIEx;
using WinUIEx.Messaging;
using Task = System.Threading.Tasks.Task;
#nullable enable
-#pragma warning disable CA1854 // Prefer the 'IDictionary.TryGetValue(TKey, out TValue)' method
namespace Rebound.Defrag;
@@ -77,19 +72,13 @@ public async Task LoadAppAsync()
timer.Start();
// Check if the application is running with administrator privileges
- IsAdministrator();
+ _ = IsAdministrator();
CheckTask();
}
- public static void SetProgressState(TaskbarProgressBarState state)
- {
- TaskbarManager.Instance.SetProgressState(state);
- }
+ public static void SetProgressState(TaskbarProgressBarState state) => TaskbarManager.Instance.SetProgressState(state);
- public static void SetProgressValue(int completed, int total)
- {
- TaskbarManager.Instance.SetProgressValue(completed, total);
- }
+ public static void SetProgressValue(int completed, int total) => TaskbarManager.Instance.SetProgressValue(completed, total);
private async void MessageReceived(object? sender, WindowMessageEventArgs e)
{
@@ -165,10 +154,7 @@ public bool IsAdministrator()
return principal.IsInRole(WindowsBuiltInRole.Administrator);
}
- private void ListviewSelectionChange(object sender, SelectionChangedEventArgs args)
- {
- LoadSelectedItemInfo(GetStatus());
- }
+ private void ListviewSelectionChange(object sender, SelectionChangedEventArgs args) => LoadSelectedItemInfo(GetStatus());
public string GetLastOptimizeDate()
{
@@ -195,14 +181,7 @@ public string GetLastOptimizeDate()
public void LoadSelectedItemInfo(string status, string info = "....")
{
- if (info == "....")
- {
- info = GetLastOptimizeDate();
- }
- else
- {
- info = "Unknown....";
- }
+ info = info == "...." ? GetLastOptimizeDate() : "Unknown....";
if (MyListView.SelectedItem != null)
{
var selectedItem = MyListView.SelectedItem as DiskItem;
@@ -459,7 +438,7 @@ public static string ConvertStringToNumericRepresentation(string input)
foreach (var c in input)
{
// Convert the character to its ASCII value and append it
- numericRepresentation.Append((int)c);
+ _ = numericRepresentation.Append((int)c);
}
// Return the numeric representation as a string
@@ -597,10 +576,7 @@ public static string GetDriveTypeDescriptionAsync(string driveRoot)
};
}
- private void Button_Click(object sender, SplitButtonClickEventArgs e)
- {
- OptimizeSelected(AdvancedView.IsOn);
- }
+ private void Button_Click(object sender, SplitButtonClickEventArgs e) => OptimizeSelected(AdvancedView.IsOn);
public static void RestartAsAdmin(string args)
{
@@ -619,7 +595,7 @@ public static void RestartAsAdmin(string args)
try
{
- Process.Start(startInfo);
+ _ = Process.Start(startInfo);
App.Current.Exit();
}
catch
@@ -697,14 +673,14 @@ void UpdateOutput(object sender, DataReceivedEventArgs args)
if (!string.IsNullOrEmpty(args.Data))
{
// Use the dispatcher to update the UI
- DispatcherQueue.TryEnqueue(() => { UpdateIO(args.Data); });
+ _ = DispatcherQueue.TryEnqueue(() => { UpdateIO(args.Data); });
// Store the output data
outputData = "\n" + args.Data;
}
}
- process.Start();
+ _ = process.Start();
process.BeginOutputReadLine();
Lock(false, "", true);
@@ -723,7 +699,7 @@ void UpdateIO(string data)
var dataToReplace = " complete.";
- DispatcherQueue.TryEnqueue(() => { RunUpdate(a, dataToReplace); });
+ _ = DispatcherQueue.TryEnqueue(() => { RunUpdate(a, dataToReplace); });
}
}
@@ -785,7 +761,7 @@ static string KeepOnlyNumbers(string input)
{
if (char.IsDigit(c))
{
- sb.Append(c);
+ _ = sb.Append(c);
}
}
@@ -884,14 +860,14 @@ void UpdateOutput(object sender, DataReceivedEventArgs args)
if (!string.IsNullOrEmpty(args.Data))
{
// Use the dispatcher to update the UI
- DispatcherQueue.TryEnqueue(() => { UpdateIO(args.Data); });
+ _ = DispatcherQueue.TryEnqueue(() => { UpdateIO(args.Data); });
// Store the output data
outputData = "\n" + args.Data;
}
}
- process.Start();
+ _ = process.Start();
process.BeginOutputReadLine();
Lock(false, "", true);
@@ -910,7 +886,7 @@ void UpdateIO(string data)
var dataToReplace = " complete.";
- DispatcherQueue.TryEnqueue(() => { RunUpdate(a, dataToReplace); });
+ _ = DispatcherQueue.TryEnqueue(() => { RunUpdate(a, dataToReplace); });
}
}
@@ -993,15 +969,9 @@ private async void ShowMessage(string message)
}
}
- private void MenuFlyoutItem_Click(object sender, RoutedEventArgs e)
- {
- OptimizeSelected(AdvancedView.IsOn);
- }
+ private void MenuFlyoutItem_Click(object sender, RoutedEventArgs e) => OptimizeSelected(AdvancedView.IsOn);
- private void MenuFlyoutItem_Click_1(object sender, RoutedEventArgs e)
- {
- OptimizeAll(false, AdvancedView.IsOn);
- }
+ private void MenuFlyoutItem_Click_1(object sender, RoutedEventArgs e) => OptimizeAll(false, AdvancedView.IsOn);
private void Button_Click_1(object sender, RoutedEventArgs e)
{
@@ -1020,14 +990,7 @@ public async void CheckTask()
try
{
ScheduledOptimizationDetails.Text = GetTaskFrequency();
- if (GetTaskFrequency() is not "Off")
- {
- ScheduledTaskText.Text = "Configure";
- }
- else
- {
- ScheduledTaskText.Text = "Turn on";
- }
+ ScheduledTaskText.Text = GetTaskFrequency() is not "Off" ? "Configure" : "Turn on";
CheckTask();
}
@@ -1043,10 +1006,7 @@ public void OpenTaskWindow()
Win32Helper.CreateModalWindow(this, win, true, true);
}
- private void Button_Click_2(object sender, RoutedEventArgs e)
- {
- LoadSelectedItemInfo(GetStatus());
- }
+ private void Button_Click_2(object sender, RoutedEventArgs e) => LoadSelectedItemInfo(GetStatus());
private async void AdvancedView_Toggled(object sender, RoutedEventArgs e)
{
@@ -1054,10 +1014,7 @@ private async void AdvancedView_Toggled(object sender, RoutedEventArgs e)
await LoadData(AdvancedView.IsOn);
}
- private async void MenuFlyoutItem_Click_2(object sender, RoutedEventArgs e)
- {
- await Launcher.LaunchUriAsync(new Uri("https://ivirius.vercel.app/docs/rebound11/defragment-and-optimize-drives/"));
- }
+ private async void MenuFlyoutItem_Click_2(object sender, RoutedEventArgs e) => await Launcher.LaunchUriAsync(new Uri("https://ivirius.vercel.app/docs/rebound11/defragment-and-optimize-drives/"));
private void CheckBox_Click(object? sender, RoutedEventArgs e)
{
@@ -1065,7 +1022,7 @@ private void CheckBox_Click(object? sender, RoutedEventArgs e)
var isChecked = ((CheckBox?)sender)?.IsChecked;
if (name != null && isChecked != null)
{
- WriteBoolToLocalSettings(ConvertStringToNumericRepresentation(name), (bool)isChecked);
+ _ = WriteBoolToLocalSettings(ConvertStringToNumericRepresentation(name), (bool)isChecked);
}
}
@@ -1137,7 +1094,7 @@ public static string GetTaskCommand()
private void MenuFlyoutItem_Click_3(object sender, RoutedEventArgs e)
{
- Process.Start("dfrgui.exe");
+ _ = Process.Start("dfrgui.exe");
Close();
}
}
diff --git a/Defrag/ScheduledOptimization.xaml.cs b/Defrag/ScheduledOptimization.xaml.cs
index d182cf2..3ef1eff 100644
--- a/Defrag/ScheduledOptimization.xaml.cs
+++ b/Defrag/ScheduledOptimization.xaml.cs
@@ -12,413 +12,354 @@
#nullable enable
-namespace Rebound.Defrag
+namespace Rebound.Defrag;
+
+public sealed partial class ScheduledOptimization : WindowEx
{
- public sealed partial class ScheduledOptimization : WindowEx
+ public ScheduledOptimization(int parentX, int parentY)
{
- public ScheduledOptimization(int parentX, int parentY)
+ this.InitializeComponent();
+ Win32Helper.RemoveIcon(this);
+ IsMaximizable = false;
+ IsMinimizable = false;
+ this.MoveAndResize(parentX + 50, parentY + 50, 550, 600);
+ IsResizable = false;
+ Title = "Scheduled optimization";
+ SystemBackdrop = new MicaBackdrop();
+ AppWindow.DefaultTitleBarShouldMatchAppModeTheme = true;
+ LoadData();
+ if (GetTaskFrequency() is not "Off")
{
- this.InitializeComponent();
- Win32Helper.RemoveIcon(this);
- IsMaximizable = false;
- IsMinimizable = false;
- this.MoveAndResize(parentX + 50, parentY + 50, 550, 600);
- IsResizable = false;
- Title = "Scheduled optimization";
- SystemBackdrop = new MicaBackdrop();
- AppWindow.DefaultTitleBarShouldMatchAppModeTheme = true;
- LoadData();
- if (GetTaskFrequency() is not "Off")
+ EnableTaskSwitch.IsOn = true;
+ if (GetTaskFrequency().Contains("daily", StringComparison.CurrentCultureIgnoreCase))
{
- EnableTaskSwitch.IsOn = true;
- if (GetTaskFrequency().Contains("daily", StringComparison.CurrentCultureIgnoreCase))
- {
- Frequency.SelectedIndex = 0;
- }
- if (GetTaskFrequency().Contains("weekly", StringComparison.CurrentCultureIgnoreCase))
- {
- Frequency.SelectedIndex = 1;
- }
- if (GetTaskFrequency().Contains("monthly", StringComparison.CurrentCultureIgnoreCase))
- {
- Frequency.SelectedIndex = 2;
- }
+ Frequency.SelectedIndex = 0;
+ }
+ if (GetTaskFrequency().Contains("weekly", StringComparison.CurrentCultureIgnoreCase))
+ {
+ Frequency.SelectedIndex = 1;
+ }
+ if (GetTaskFrequency().Contains("monthly", StringComparison.CurrentCultureIgnoreCase))
+ {
+ Frequency.SelectedIndex = 2;
}
- CheckIsOn();
- CheckData();
}
+ CheckIsOn();
+ CheckData();
+ }
- public async void CheckData()
+ public async void CheckData()
+ {
+ await Task.Delay(500);
+
+ if (GetTaskCommand().Contains("/E"))
{
- await Task.Delay(500);
+ OptimizeNew.IsChecked = true;
+ foreach (var disk in (List)MyListView.ItemsSource)
+ {
+ var letter = disk.DriveLetter != null && disk.DriveLetter.EndsWith('\\') ? disk.DriveLetter[..^1] : disk.DriveLetter;
+ disk.IsChecked = letter == null || !GetTaskCommand().Contains(letter);
+ }
+ }
+ else
+ {
+ OptimizeNew.IsChecked = false;
+ foreach (var disk in (List)MyListView.ItemsSource)
+ {
+ var letter = disk.DriveLetter != null && disk.DriveLetter.EndsWith('\\') ? disk.DriveLetter[..^1] : disk.DriveLetter;
+ disk.IsChecked = letter != null && GetTaskCommand().Contains(letter);
+ }
+ }
+ CheckSelectAll();
+ }
+
+ public static void ScheduleDefragTask(List items, bool optimizeNewDrives, string scheduleFrequency)
+ {
+ using TaskService ts = new();
+ // Create or open the Defrag folder in Task Scheduler
+ var defragFolder = ts.GetFolder(@"\Microsoft\Windows\Defrag");
+
+ // Retrieve the ScheduledDefrag task if it exists
+ var scheduledDefrag = defragFolder.GetTasks()["ScheduledDefrag"];
+
+ // If the task exists, we'll modify it
+ TaskDefinition td;
+ if (scheduledDefrag != null)
+ {
+ td = scheduledDefrag.Definition;
+ }
+ else
+ {
+ td = ts.NewTask();
+ td.RegistrationInfo.Description = "Scheduled Defrag Task";
+ td.Settings.Priority = ProcessPriorityClass.High;
+ td.Settings.Volatile = false;
+ td.Settings.RunOnlyIfLoggedOn = false;
+ }
- if (GetTaskCommand().Contains("/E"))
+ // Set triggers based on the scheduleFrequency input
+ td.Triggers.Clear();
+ _ = scheduleFrequency.ToLower() switch
+ {
+ "daily" => td.Triggers.Add(new DailyTrigger { DaysInterval = 1 }),
+ "weekly" => td.Triggers.Add(new WeeklyTrigger { DaysOfWeek = DaysOfTheWeek.Sunday }),
+ "monthly" => td.Triggers.Add(new MonthlyTrigger { DaysOfMonth = [1] }),
+ _ => throw new ArgumentException("Invalid schedule frequency"),
+ };
+
+ // Build the defrag command with selected drives
+ if (optimizeNewDrives == true)
+ {
+ List drives = [];
+ foreach (var disk in items)
{
- OptimizeNew.IsChecked = true;
- foreach (var disk in (List)MyListView.ItemsSource)
+ if (disk.IsChecked == false)
{
- string? letter;
- if (disk.DriveLetter != null && disk.DriveLetter.EndsWith('\\'))
- {
- letter = disk.DriveLetter[..^1];
- }
- else
- {
- letter = disk.DriveLetter;
- }
- if (letter != null && GetTaskCommand().Contains(letter))
+ var letter = disk.DriveLetter != null && disk.DriveLetter.EndsWith('\\') ? disk.DriveLetter[..^1] : disk.DriveLetter;
+ if (letter != null)
{
- disk.IsChecked = false;
- }
- else
- {
- disk.IsChecked = true;
+ drives.Add(letter);
}
}
}
- else
+ var defragCommand = string.Join(" ", drives);
+ td.Actions.Clear();
+ _ = td.Actions.Add(new ExecAction("%SystemRoot%\\System32\\defrag.exe", $"/E {defragCommand}", null)); // Optimizing the drives
+ }
+ else
+ {
+ List drives = [];
+ foreach (var disk in items)
{
- OptimizeNew.IsChecked = false;
- foreach (var disk in (List)MyListView.ItemsSource)
+ if (disk.IsChecked == true)
{
- string? letter;
- if (disk.DriveLetter != null && disk.DriveLetter.EndsWith('\\'))
- {
- letter = disk.DriveLetter[..^1];
- }
- else
- {
- letter = disk.DriveLetter;
- }
- if (letter != null && GetTaskCommand().Contains(letter))
+ var letter = disk.DriveLetter != null && disk.DriveLetter.EndsWith('\\') ? disk.DriveLetter[..^1] : disk.DriveLetter;
+ if (letter != null)
{
- disk.IsChecked = true;
- }
- else
- {
- disk.IsChecked = false;
+ drives.Add(letter);
}
}
}
- CheckSelectAll();
+ var defragCommand = string.Join(" ", drives);
+ td.Actions.Clear();
+ _ = td.Actions.Add(new ExecAction("%SystemRoot%\\System32\\defrag.exe", $"{defragCommand} /O", null)); // Optimizing the drives
}
- public static void ScheduleDefragTask(List items, bool optimizeNewDrives, string scheduleFrequency)
- {
- using (TaskService ts = new())
- {
- // Create or open the Defrag folder in Task Scheduler
- TaskFolder defragFolder = ts.GetFolder(@"\Microsoft\Windows\Defrag");
+ // Register or update the task
+ _ = defragFolder.RegisterTaskDefinition("ScheduledDefrag", td);
- // Retrieve the ScheduledDefrag task if it exists
- Microsoft.Win32.TaskScheduler.Task scheduledDefrag = defragFolder.GetTasks()["ScheduledDefrag"];
+ // Retrieve the ScheduledDefrag task if it exists
+ var newScheduledDefrag = defragFolder.GetTasks()["ScheduledDefrag"];
- // If the task exists, we'll modify it
- TaskDefinition td;
- if (scheduledDefrag != null)
- {
- td = scheduledDefrag.Definition;
- }
- else
- {
- td = ts.NewTask();
- td.RegistrationInfo.Description = "Scheduled Defrag Task";
- td.Settings.Priority = ProcessPriorityClass.High;
- td.Settings.Volatile = false;
- td.Settings.RunOnlyIfLoggedOn = false;
- }
+ newScheduledDefrag.Enabled = true;
+ }
- // Set triggers based on the scheduleFrequency input
- td.Triggers.Clear();
- switch (scheduleFrequency.ToLower())
- {
- case "daily":
- td.Triggers.Add(new DailyTrigger { DaysInterval = 1 });
- break;
- case "weekly":
- td.Triggers.Add(new WeeklyTrigger { DaysOfWeek = DaysOfTheWeek.Sunday });
- break;
- case "monthly":
- td.Triggers.Add(new MonthlyTrigger { DaysOfMonth = [1] });
- break;
- default:
- throw new ArgumentException("Invalid schedule frequency");
- }
+ public static void TurnOffDefragTask()
+ {
+ using TaskService ts = new();
+ // Create or open the Defrag folder in Task Scheduler
+ var defragFolder = ts.GetFolder(@"\Microsoft\Windows\Defrag");
- // Build the defrag command with selected drives
- if (optimizeNewDrives == true)
- {
- List drives = [];
- foreach (DiskItem disk in items)
- {
- if (disk.IsChecked == false)
- {
- string? letter;
- if (disk.DriveLetter != null && disk.DriveLetter.EndsWith('\\'))
- {
- letter = disk.DriveLetter[..^1];
- }
- else
- {
- letter = disk.DriveLetter;
- }
- if (letter != null) drives.Add(letter);
- }
- }
- string defragCommand = string.Join(" ", drives);
- td.Actions.Clear();
- td.Actions.Add(new ExecAction("%SystemRoot%\\System32\\defrag.exe", $"/E {defragCommand}", null)); // Optimizing the drives
- }
- else
- {
- List drives = [];
- foreach (DiskItem disk in items)
- {
- if (disk.IsChecked == true)
- {
- string? letter;
- if (disk.DriveLetter != null && disk.DriveLetter.EndsWith('\\'))
- {
- letter = disk.DriveLetter[..^1];
- }
- else
- {
- letter = disk.DriveLetter;
- }
- if (letter != null) drives.Add(letter);
- }
- }
- string defragCommand = string.Join(" ", drives);
- td.Actions.Clear();
- td.Actions.Add(new ExecAction("%SystemRoot%\\System32\\defrag.exe", $"{defragCommand} /O", null)); // Optimizing the drives
- }
+ // Retrieve the ScheduledDefrag task if it exists
+ var scheduledDefrag = defragFolder.GetTasks()["ScheduledDefrag"];
- // Register or update the task
- defragFolder.RegisterTaskDefinition("ScheduledDefrag", td);
+ scheduledDefrag.Enabled = false;
+ }
- // Retrieve the ScheduledDefrag task if it exists
- Microsoft.Win32.TaskScheduler.Task newScheduledDefrag = defragFolder.GetTasks()["ScheduledDefrag"];
+ public async void LoadData()
+ {
+ // Initial delay
+ // Essential for ensuring the UI loads before starting tasks
+ await Task.Delay(100);
- newScheduledDefrag.Enabled = true;
- }
- }
+ List items = [];
- public static void TurnOffDefragTask()
+ // Get the logical drives bitmask
+ var drivesBitMask = Win32Helper.GetLogicalDrives();
+ if (drivesBitMask == 0)
{
- using (TaskService ts = new())
- {
- // Create or open the Defrag folder in Task Scheduler
- TaskFolder defragFolder = ts.GetFolder(@"\Microsoft\Windows\Defrag");
-
- // Retrieve the ScheduledDefrag task if it exists
- Microsoft.Win32.TaskScheduler.Task scheduledDefrag = defragFolder.GetTasks()["ScheduledDefrag"];
-
- scheduledDefrag.Enabled = false;
- }
+ return;
}
- public async void LoadData()
+ for (var driveLetter = 'A'; driveLetter <= 'Z'; driveLetter++)
{
- // Initial delay
- // Essential for ensuring the UI loads before starting tasks
- await Task.Delay(100);
-
- List items = [];
-
- // Get the logical drives bitmask
- uint drivesBitMask = Win32Helper.GetLogicalDrives();
- if (drivesBitMask == 0)
+ var mask = 1u << (driveLetter - 'A');
+ if ((drivesBitMask & mask) != 0)
{
- return;
- }
+ var drive = $"{driveLetter}:\\";
- for (char driveLetter = 'A'; driveLetter <= 'Z'; driveLetter++)
- {
- uint mask = 1u << (driveLetter - 'A');
- if ((drivesBitMask & mask) != 0)
+ StringBuilder volumeName = new(261);
+ StringBuilder fileSystemName = new(261);
+ if (Win32Helper.GetVolumeInformation(drive, volumeName, volumeName.Capacity, out _, out _, out _, fileSystemName, fileSystemName.Capacity))
{
- string drive = $"{driveLetter}:\\";
+ var newDriveLetter = drive.ToString().Remove(2, 1);
+ var mediaType = GetDriveTypeDescriptionAsync(drive);
- StringBuilder volumeName = new(261);
- StringBuilder fileSystemName = new(261);
- if (Win32Helper.GetVolumeInformation(drive, volumeName, volumeName.Capacity, out _, out _, out _, fileSystemName, fileSystemName.Capacity))
+ if (volumeName.ToString() != string.Empty)
{
- var newDriveLetter = drive.ToString().Remove(2, 1);
- string mediaType = GetDriveTypeDescriptionAsync(drive);
-
- if (volumeName.ToString() != string.Empty)
+ var item = new DiskItem
{
- var item = new DiskItem
- {
- Name = $"{volumeName} ({newDriveLetter})",
- ImagePath = "ms-appx:///Assets/Drive.png",
- MediaType = mediaType,
- DriveLetter = drive,
- };
- if (item.MediaType == "Removable")
- {
- item.ImagePath = "ms-appx:///Assets/DriveRemovable.png";
- }
- if (item.MediaType == "Unknown")
- {
- item.ImagePath = "ms-appx:///Assets/DriveUnknown.png";
- }
- if (item.MediaType == "CD-ROM")
- {
- item.ImagePath = "ms-appx:///Assets/DriveOptical.png";
- }
- if (item.DriveLetter.Contains('C'))
- {
- item.ImagePath = "ms-appx:///Assets/DriveWindows.png";
- }
- items.Add(item);
+ Name = $"{volumeName} ({newDriveLetter})",
+ ImagePath = "ms-appx:///Assets/Drive.png",
+ MediaType = mediaType,
+ DriveLetter = drive,
+ };
+ if (item.MediaType == "Removable")
+ {
+ item.ImagePath = "ms-appx:///Assets/DriveRemovable.png";
}
- else
+ if (item.MediaType == "Unknown")
{
- var item = new DiskItem
- {
- Name = $"({newDriveLetter})",
- ImagePath = "ms-appx:///Assets/Drive.png",
- MediaType = mediaType,
- DriveLetter = drive,
- };
- if (item.MediaType == "Removable")
- {
- item.ImagePath = "ms-appx:///Assets/DriveRemovable.png";
- }
- if (item.MediaType == "Unknown")
- {
- item.ImagePath = "ms-appx:///Assets/DriveUnknown.png";
- }
- if (item.MediaType == "CD-ROM")
- {
- item.ImagePath = "ms-appx:///Assets/DriveOptical.png";
- }
- if (item.DriveLetter.Contains('C'))
- {
- item.ImagePath = "ms-appx:///Assets/DriveWindows.png";
- }
- items.Add(item);
+ item.ImagePath = "ms-appx:///Assets/DriveUnknown.png";
}
+ if (item.MediaType == "CD-ROM")
+ {
+ item.ImagePath = "ms-appx:///Assets/DriveOptical.png";
+ }
+ if (item.DriveLetter.Contains('C'))
+ {
+ item.ImagePath = "ms-appx:///Assets/DriveWindows.png";
+ }
+ items.Add(item);
}
else
{
- Debug.WriteLine($" Failed to get volume information for {drive}");
+ var item = new DiskItem
+ {
+ Name = $"({newDriveLetter})",
+ ImagePath = "ms-appx:///Assets/Drive.png",
+ MediaType = mediaType,
+ DriveLetter = drive,
+ };
+ if (item.MediaType == "Removable")
+ {
+ item.ImagePath = "ms-appx:///Assets/DriveRemovable.png";
+ }
+ if (item.MediaType == "Unknown")
+ {
+ item.ImagePath = "ms-appx:///Assets/DriveUnknown.png";
+ }
+ if (item.MediaType == "CD-ROM")
+ {
+ item.ImagePath = "ms-appx:///Assets/DriveOptical.png";
+ }
+ if (item.DriveLetter.Contains('C'))
+ {
+ item.ImagePath = "ms-appx:///Assets/DriveWindows.png";
+ }
+ items.Add(item);
}
}
+ else
+ {
+ Debug.WriteLine($" Failed to get volume information for {drive}");
+ }
}
+ }
- int selIndex = MyListView.SelectedIndex is not -1 ? MyListView.SelectedIndex : 0;
+ int selIndex = MyListView.SelectedIndex is not -1 ? MyListView.SelectedIndex : 0;
- // Set the list view's item source
- MyListView.ItemsSource = items;
+ // Set the list view's item source
+ MyListView.ItemsSource = items;
- MyListView.SelectedIndex = selIndex >= items.Count ? items.Count - 1 : selIndex;
- }
+ MyListView.SelectedIndex = selIndex >= items.Count ? items.Count - 1 : selIndex;
+ }
- private void Button_Click(object sender, Microsoft.UI.Xaml.RoutedEventArgs e)
- {
- OptimizeNew.IsChecked ??= true;
+ private void Button_Click(object sender, Microsoft.UI.Xaml.RoutedEventArgs e)
+ {
+ OptimizeNew.IsChecked ??= true;
- var frequencyItem = Frequency.SelectedItem as ComboBoxItem;
- string frequencyContent = frequencyItem?.Content?.ToString() ?? string.Empty;
+ var frequencyItem = Frequency.SelectedItem as ComboBoxItem;
+ var frequencyContent = frequencyItem?.Content?.ToString() ?? string.Empty;
- if (EnableTaskSwitch.IsOn == true)
- {
- ScheduleDefragTask((List?)MyListView.ItemsSource ?? [], OptimizeNew.IsChecked ?? false, frequencyContent);
- Close();
- return;
- }
- else
- {
- TurnOffDefragTask();
- Close();
- return;
- }
+ if (EnableTaskSwitch.IsOn == true)
+ {
+ ScheduleDefragTask((List?)MyListView.ItemsSource ?? [], OptimizeNew.IsChecked ?? false, frequencyContent);
+ Close();
+ return;
}
-
- private void Button_Click_1(object sender, Microsoft.UI.Xaml.RoutedEventArgs e)
+ else
{
+ TurnOffDefragTask();
Close();
+ return;
}
+ }
+
+ private void Button_Click_1(object sender, Microsoft.UI.Xaml.RoutedEventArgs e) => Close();
+
+ private void EnableTaskSwitch_Toggled(object sender, Microsoft.UI.Xaml.RoutedEventArgs e) => CheckIsOn();
- private void EnableTaskSwitch_Toggled(object sender, Microsoft.UI.Xaml.RoutedEventArgs e)
+ public void CheckIsOn() => MyListView.IsEnabled = Frequency.IsEnabled = OptimizeNew.IsEnabled = SelectAllBox.IsEnabled = EnableTaskSwitch.IsOn;
+
+ private async void CheckBox_Checked(object sender, Microsoft.UI.Xaml.RoutedEventArgs e)
+ {
+ await Task.Delay(50);
+ CheckSelectAll();
+ }
+
+ public void CheckSelectAll()
+ {
+ var checkedItems = 0;
+ foreach (var item in (List)MyListView.ItemsSource)
{
- CheckIsOn();
+ if (item.IsChecked == true)
+ {
+ checkedItems++;
+ }
}
-
- public void CheckIsOn()
+ if (checkedItems == ((List)MyListView.ItemsSource).Count)
{
- MyListView.IsEnabled = Frequency.IsEnabled = OptimizeNew.IsEnabled = SelectAllBox.IsEnabled = EnableTaskSwitch.IsOn;
+ SelectAllBox.IsChecked = true;
+ return;
}
-
- private async void CheckBox_Checked(object sender, Microsoft.UI.Xaml.RoutedEventArgs e)
+ else if (checkedItems == 0)
{
- await Task.Delay(50);
- CheckSelectAll();
+ SelectAllBox.IsChecked = false;
+ return;
}
-
- public void CheckSelectAll()
+ else
{
- int checkedItems = 0;
- foreach (var item in (List)MyListView.ItemsSource)
- {
- if (item.IsChecked == true)
- checkedItems++;
- }
- if (checkedItems == ((List)MyListView.ItemsSource).Count)
- {
- SelectAllBox.IsChecked = true;
- return;
- }
- else if (checkedItems == 0)
- {
- SelectAllBox.IsChecked = false;
- return;
- }
- else
- {
- SelectAllBox.IsChecked = null;
- return;
- }
+ SelectAllBox.IsChecked = null;
+ return;
}
+ }
- private async void CheckBox_Checked_1(object sender, Microsoft.UI.Xaml.RoutedEventArgs e)
+ private async void CheckBox_Checked_1(object sender, Microsoft.UI.Xaml.RoutedEventArgs e)
+ {
+ await Task.Delay(50);
+ List list = [];
+ if (SelectAllBox.IsChecked == true)
{
- await Task.Delay(50);
- List list = [];
- if (SelectAllBox.IsChecked == true)
+ foreach (var item in (List)MyListView.ItemsSource)
{
- foreach (var item in (List)MyListView.ItemsSource)
+ list.Add(new()
{
- list.Add(new()
- {
- DriveLetter = item.DriveLetter,
- ImagePath = item.ImagePath,
- IsChecked = true,
- MediaType = item.MediaType,
- Name = item.Name,
- ProgressValue = item.ProgressValue,
- });
- }
+ DriveLetter = item.DriveLetter,
+ ImagePath = item.ImagePath,
+ IsChecked = true,
+ MediaType = item.MediaType,
+ Name = item.Name,
+ ProgressValue = item.ProgressValue,
+ });
}
- else if (SelectAllBox.IsChecked == false)
+ }
+ else if (SelectAllBox.IsChecked == false)
+ {
+ foreach (var item in (List)MyListView.ItemsSource)
{
- foreach (var item in (List)MyListView.ItemsSource)
+ list.Add(new()
{
- list.Add(new()
- {
- DriveLetter = item.DriveLetter,
- ImagePath = item.ImagePath,
- IsChecked = false,
- MediaType = item.MediaType,
- Name = item.Name,
- ProgressValue = item.ProgressValue,
- });
- }
+ DriveLetter = item.DriveLetter,
+ ImagePath = item.ImagePath,
+ IsChecked = false,
+ MediaType = item.MediaType,
+ Name = item.Name,
+ ProgressValue = item.ProgressValue,
+ });
}
- MyListView.ItemsSource = list;
- CheckSelectAll();
}
+ MyListView.ItemsSource = list;
+ CheckSelectAll();
}
}
diff --git a/Delivery/AppRT/Products/Associated/RunBox.ico b/Delivery/AppRT/Products/Associated/RunBox.ico
index 1150f55..5d1935f 100644
Binary files a/Delivery/AppRT/Products/Associated/RunBox.ico and b/Delivery/AppRT/Products/Associated/RunBox.ico differ
diff --git a/Delivery/AppRT/Products/Associated/rcontrol.ico b/Delivery/AppRT/Products/Associated/rcontrol.ico
index 64b26f5..809b068 100644
Binary files a/Delivery/AppRT/Products/Associated/rcontrol.ico and b/Delivery/AppRT/Products/Associated/rcontrol.ico differ
diff --git a/Delivery/AppRT/Products/Control.png b/Delivery/AppRT/Products/Control.png
index 847977c..965e17b 100644
Binary files a/Delivery/AppRT/Products/Control.png and b/Delivery/AppRT/Products/Control.png differ
diff --git a/Delivery/AppRT/Products/EventViewer.png b/Delivery/AppRT/Products/EventViewer.png
index 4af79d0..93376df 100644
Binary files a/Delivery/AppRT/Products/EventViewer.png and b/Delivery/AppRT/Products/EventViewer.png differ
diff --git a/Delivery/AppRT/Products/ResourceMonitor.png b/Delivery/AppRT/Products/ResourceMonitor.png
index 7751ce3..3787656 100644
Binary files a/Delivery/AppRT/Products/ResourceMonitor.png and b/Delivery/AppRT/Products/ResourceMonitor.png differ
diff --git a/Delivery/AppRT/Products/TaskScheduler.png b/Delivery/AppRT/Products/TaskScheduler.png
index d2e2f35..02e8744 100644
Binary files a/Delivery/AppRT/Products/TaskScheduler.png and b/Delivery/AppRT/Products/TaskScheduler.png differ
diff --git a/Delivery/Reserved/Extended/Rebound.About.msix b/Delivery/Reserved/Extended/Rebound.About.msix
index af6478d..e774319 100644
Binary files a/Delivery/Reserved/Extended/Rebound.About.msix and b/Delivery/Reserved/Extended/Rebound.About.msix differ
diff --git a/Delivery/Reserved/Extended/Rebound.Cleanup.msix b/Delivery/Reserved/Extended/Rebound.Cleanup.msix
index 3593a44..b73246f 100644
Binary files a/Delivery/Reserved/Extended/Rebound.Cleanup.msix and b/Delivery/Reserved/Extended/Rebound.Cleanup.msix differ
diff --git a/Delivery/Reserved/Extended/Rebound.Defrag.msix b/Delivery/Reserved/Extended/Rebound.Defrag.msix
index a9b063b..841cf86 100644
Binary files a/Delivery/Reserved/Extended/Rebound.Defrag.msix and b/Delivery/Reserved/Extended/Rebound.Defrag.msix differ
diff --git a/Delivery/Reserved/Extended/Rebound.Run.msix b/Delivery/Reserved/Extended/Rebound.Run.msix
index 7820d69..502a204 100644
Binary files a/Delivery/Reserved/Extended/Rebound.Run.msix and b/Delivery/Reserved/Extended/Rebound.Run.msix differ
diff --git a/Delivery/Reserved/Extended/Rebound.TrustedPlatform.msix b/Delivery/Reserved/Extended/Rebound.TrustedPlatform.msix
index 162418a..88f405b 100644
Binary files a/Delivery/Reserved/Extended/Rebound.TrustedPlatform.msix and b/Delivery/Reserved/Extended/Rebound.TrustedPlatform.msix differ
diff --git a/ExplorerPhotoPrintingDialog/App.xaml.cs b/ExplorerPhotoPrintingDialog/App.xaml.cs
index 7071344..b15b191 100644
--- a/ExplorerPhotoPrintingDialog/App.xaml.cs
+++ b/ExplorerPhotoPrintingDialog/App.xaml.cs
@@ -1,20 +1,4 @@
-using System;
-using System.Collections.Generic;
-using System.IO;
-using System.Linq;
-using System.Runtime.InteropServices.WindowsRuntime;
-using Microsoft.UI.Xaml;
-using Microsoft.UI.Xaml.Controls;
-using Microsoft.UI.Xaml.Controls.Primitives;
-using Microsoft.UI.Xaml.Data;
-using Microsoft.UI.Xaml.Input;
-using Microsoft.UI.Xaml.Media;
-using Microsoft.UI.Xaml.Navigation;
-using Microsoft.UI.Xaml.Shapes;
-using Windows.ApplicationModel;
-using Windows.ApplicationModel.Activation;
-using Windows.Foundation;
-using Windows.Foundation.Collections;
+using Microsoft.UI.Xaml;
// To learn more about WinUI, the WinUI project structure,
// and more about our project templates, see: http://aka.ms/winui-project-info.
@@ -31,7 +15,7 @@ public partial class App : Application
///
public App()
{
- this.InitializeComponent();
+ InitializeComponent();
}
///
diff --git a/ExplorerPhotoPrintingDialog/MainWindow.xaml.cs b/ExplorerPhotoPrintingDialog/MainWindow.xaml.cs
index efa668f..39bdec1 100644
--- a/ExplorerPhotoPrintingDialog/MainWindow.xaml.cs
+++ b/ExplorerPhotoPrintingDialog/MainWindow.xaml.cs
@@ -1,5 +1,4 @@
using System;
-using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing.Printing;
using System.IO;
@@ -9,15 +8,8 @@
using System.Threading.Tasks;
using Microsoft.UI.Xaml;
using Microsoft.UI.Xaml.Controls;
-using Microsoft.UI.Xaml.Controls.Primitives;
-using Microsoft.UI.Xaml.Data;
-using Microsoft.UI.Xaml.Input;
-using Microsoft.UI.Xaml.Media;
using Microsoft.UI.Xaml.Media.Imaging;
-using Microsoft.UI.Xaml.Navigation;
using Microsoft.UI.Xaml.Printing;
-using Windows.Foundation;
-using Windows.Foundation.Collections;
using Windows.Graphics.Printing;
using PrintDocument = Microsoft.UI.Xaml.Printing.PrintDocument;
@@ -32,13 +24,13 @@ public sealed partial class MainWindow : Window
{
public MainWindow()
{
- this.InitializeComponent();
+ InitializeComponent();
}
public async Task RenderUIElementToBytes(FrameworkElement element)
{
// Create a RenderTargetBitmap object
- RenderTargetBitmap renderTargetBitmap = new RenderTargetBitmap();
+ var renderTargetBitmap = new RenderTargetBitmap();
// Render the element
await renderTargetBitmap.RenderAsync(element);
@@ -47,7 +39,7 @@ public async Task RenderUIElementToBytes(FrameworkElement element)
var pixelBuffer = await renderTargetBitmap.GetPixelsAsync();
// Convert the pixel buffer to byte array
- byte[] pixels = pixelBuffer.ToArray();
+ var pixels = pixelBuffer.ToArray();
// You can now use these bytes to send to the printer
return pixels;
@@ -59,7 +51,10 @@ public static string GetFirstPrinterName()
foreach (string printer in PrinterSettings.InstalledPrinters)
{
if (printer.Contains("EPSON"))
+ {
return printer;
+ }
+
Debug.WriteLine(printer);
// Return the name of the first available printer
//return printer;
@@ -72,17 +67,17 @@ private async void myButton_Click(object sender, RoutedEventArgs e)
{
myButton.Content = "Clicked";
// Render the element to a byte array
- byte[] elementBytes = await RenderUIElementToBytes(fff);
+ var elementBytes = await RenderUIElementToBytes(fff);
// Allocate memory for the byte array
- IntPtr pUnmanagedBytes = Marshal.AllocCoTaskMem(elementBytes.Length);
+ var pUnmanagedBytes = Marshal.AllocCoTaskMem(elementBytes.Length);
Marshal.Copy(elementBytes, 0, pUnmanagedBytes, elementBytes.Length);
// Send the bytes to the printer
- RawPrintingService.SendStringToPrinter(GetFirstPrinterName(), "Eeeeeeeeeeeeeeeeeee");
+ _ = RawPrintingService.SendStringToPrinter(GetFirstPrinterName(), "Eeeeeeeeeeeeeeeeeee");
return;
- bool result = RawPrintingService.SendBytesToPrinter(GetFirstPrinterName(), pUnmanagedBytes, elementBytes.Length);
+ var result = RawPrintingService.SendBytesToPrinter(GetFirstPrinterName(), pUnmanagedBytes, elementBytes.Length);
/*RegisterPrint();
try
@@ -118,7 +113,7 @@ private IPrintDocumentSource printDocSource
get; set;
}
- void RegisterPrint()
+ private void RegisterPrint()
{
// Register for PrintTaskRequested event
var hWnd = WinRT.Interop.WindowNative.GetWindowHandle(this);
@@ -134,11 +129,9 @@ void RegisterPrint()
printDoc.AddPages += AddPages;
}
- private void Paginate(object sender, PaginateEventArgs e)
- {
+ private void Paginate(object sender, PaginateEventArgs e) =>
// As I only want to print one Rectangle, so I set the count to 1
printDoc.SetPreviewPageCount(1, PreviewPageCountType.Final);
- }
private void GetPreviewPage(object sender, GetPreviewPageEventArgs e)
{
@@ -146,20 +139,18 @@ private void GetPreviewPage(object sender, GetPreviewPageEventArgs e)
//printDoc.SetPreviewPage(e.PageNumber, REBItems);
}
- private async void AddPages(object sender, AddPagesEventArgs e)
- {
+ private void AddPages(object sender, AddPagesEventArgs e) =>
/*var children = REBItems.Children.ToList(); // Create a copy of the children
- foreach (FrameworkElement ui in children)
- {
- //REBItems.Children.Remove(ui); // Remove the child from the stack panel
- printDoc.AddPage(ui); // Add the child to the print document
- //await Task.Delay(200);
- }*/
+foreach (FrameworkElement ui in children)
+{
+//REBItems.Children.Remove(ui); // Remove the child from the stack panel
+printDoc.AddPage(ui); // Add the child to the print document
+//await Task.Delay(200);
+}*/
// Indicate that all of the print pages have been provided
printDoc.AddPagesComplete();
- }
private void PrintTaskCompleted(PrintTask sender, PrintTaskCompletedEventArgs args)
{
@@ -167,16 +158,16 @@ private void PrintTaskCompleted(PrintTask sender, PrintTaskCompletedEventArgs ar
// Notify the user when the print operation fails.
if (args.Completion == PrintTaskCompletion.Failed)
{
- this.DispatcherQueue.TryEnqueue(async () =>
+ _ = DispatcherQueue.TryEnqueue(async () =>
{
- ContentDialog noPrintingDialog = new ContentDialog()
+ var noPrintingDialog = new ContentDialog()
{
- XamlRoot = this.Content.XamlRoot,
+ XamlRoot = Content.XamlRoot,
Title = "Printing error",
Content = "\nSorry, failed to print.",
PrimaryButtonText = "OK"
};
- await noPrintingDialog.ShowAsync();
+ _ = await noPrintingDialog.ShowAsync();
});
}
}
@@ -192,11 +183,9 @@ private void PrintTaskRequested(PrintManager sender, PrintTaskRequestedEventArgs
printTask.Completed += PrintTaskCompleted;
}
- private void PrintTaskSourceRequrested(PrintTaskSourceRequestedArgs args)
- {
+ private void PrintTaskSourceRequrested(PrintTaskSourceRequestedArgs args) =>
// Set the document source.
args.SetSource(printDocSource);
- }
}
public class RawPrintingService
@@ -220,7 +209,7 @@ public class DOCINFOA
public static extern bool ClosePrinter(IntPtr hPrinter);
[DllImport("winspool.Drv", EntryPoint = "StartDocPrinterA", SetLastError = true, CharSet = CharSet.Unicode, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
- public static extern bool StartDocPrinter(IntPtr hPrinter, Int32 level, [In, MarshalAs(UnmanagedType.LPStruct)] DOCINFOA di);
+ public static extern bool StartDocPrinter(IntPtr hPrinter, int level, [In, MarshalAs(UnmanagedType.LPStruct)] DOCINFOA di);
[DllImport("winspool.Drv", EntryPoint = "EndDocPrinter", SetLastError = true, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
public static extern bool EndDocPrinter(IntPtr hPrinter);
@@ -232,23 +221,22 @@ public class DOCINFOA
public static extern bool EndPagePrinter(IntPtr hPrinter);
[DllImport("winspool.Drv", EntryPoint = "WritePrinter", SetLastError = true, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
- public static extern bool WritePrinter(IntPtr hPrinter, IntPtr pBytes, Int32 dwCount, out Int32 dwWritten);
+ public static extern bool WritePrinter(IntPtr hPrinter, IntPtr pBytes, int dwCount, out int dwWritten);
// SendBytesToPrinter()
// When the function is given a printer name and an unmanaged array
// of bytes, the function sends those bytes to the print queue.
// Returns true on success, false on failure.
- public static bool SendBytesToPrinter(string szPrinterName, IntPtr pBytes, Int32 dwCount)
+ public static bool SendBytesToPrinter(string szPrinterName, IntPtr pBytes, int dwCount)
{
- Int32 dwError = 0, dwWritten = 0;
- IntPtr hPrinter = new IntPtr(0);
- DOCINFOA di = new DOCINFOA();
- bool bSuccess = false; // Assume failure unless you specifically succeed.
+ _ = new IntPtr(0);
+ var di = new DOCINFOA();
+ var bSuccess = false; // Assume failure unless you specifically succeed.
di.pDocName = "RAW Document";
// Win7
di.pDataType = "RAW";
-
+ System.nint hPrinter;
// Win8+
// di.pDataType = "XPS_PASS";
@@ -262,18 +250,18 @@ public static bool SendBytesToPrinter(string szPrinterName, IntPtr pBytes, Int32
if (StartPagePrinter(hPrinter))
{
// Write your bytes.
- bSuccess = WritePrinter(hPrinter, pBytes, dwCount, out dwWritten);
- EndPagePrinter(hPrinter);
+ bSuccess = WritePrinter(hPrinter, pBytes, dwCount, out _);
+ _ = EndPagePrinter(hPrinter);
}
- EndDocPrinter(hPrinter);
+ _ = EndDocPrinter(hPrinter);
}
- ClosePrinter(hPrinter);
+ _ = ClosePrinter(hPrinter);
}
// If you did not succeed, GetLastError may give more information
// about why not.
if (bSuccess == false)
{
- dwError = Marshal.GetLastWin32Error();
+ _ = Marshal.GetLastWin32Error();
}
return bSuccess;
}
@@ -281,43 +269,41 @@ public static bool SendBytesToPrinter(string szPrinterName, IntPtr pBytes, Int32
public static bool SendFileToPrinter(string szPrinterName, string szFileName)
{
// Open the file.
- FileStream fs = new FileStream(szFileName, FileMode.Open);
+ var fs = new FileStream(szFileName, FileMode.Open);
// Create a BinaryReader on the file.
- BinaryReader br = new BinaryReader(fs);
+ var br = new BinaryReader(fs);
// Dim an array of bytes big enough to hold the file's contents.
- Byte[] bytes = new Byte[fs.Length];
- bool bSuccess = false;
+ _ = new byte[fs.Length];
// Your unmanaged pointer.
- IntPtr pUnmanagedBytes = new IntPtr(0);
+ _ = new IntPtr(0);
int nLength;
nLength = Convert.ToInt32(fs.Length);
// Read the contents of the file into the array.
- bytes = br.ReadBytes(nLength);
+ var bytes = br.ReadBytes(nLength);
// Allocate some unmanaged memory for those bytes.
- pUnmanagedBytes = Marshal.AllocCoTaskMem(nLength);
+ var pUnmanagedBytes = Marshal.AllocCoTaskMem(nLength);
// Copy the managed byte array into the unmanaged array.
Marshal.Copy(bytes, 0, pUnmanagedBytes, nLength);
// Send the unmanaged bytes to the printer.
- bSuccess = SendBytesToPrinter(szPrinterName, pUnmanagedBytes, nLength);
+ var bSuccess = SendBytesToPrinter(szPrinterName, pUnmanagedBytes, nLength);
// Free the unmanaged memory that you allocated earlier.
Marshal.FreeCoTaskMem(pUnmanagedBytes);
fs.Close();
fs.Dispose();
- fs = null;
return bSuccess;
}
public static bool SendStringToPrinter(string szPrinterName, string szString)
{
IntPtr pBytes;
- Int32 dwCount;
+ int dwCount;
// How many characters are in the string?
dwCount = szString.Length;
// Assume that the printer is expecting ANSI text, and then convert
// the string to ANSI text.
pBytes = Marshal.StringToCoTaskMemAnsi(szString);
// Send the converted ANSI string to the printer.
- SendBytesToPrinter(szPrinterName, pBytes, dwCount);
+ _ = SendBytesToPrinter(szPrinterName, pBytes, dwCount);
Marshal.FreeCoTaskMem(pBytes);
return true;
}
diff --git a/Helpers/Display.cs b/Helpers/Display.cs
index 43b69d7..eaa8bcb 100644
--- a/Helpers/Display.cs
+++ b/Helpers/Display.cs
@@ -1,5 +1,4 @@
-using WinUIEx;
-using Windows.Foundation;
+using WinUIEx;
namespace Rebound.Helpers;
diff --git a/Helpers/Registry.cs b/Helpers/Registry.cs
index 050bb22..9dc6878 100644
--- a/Helpers/Registry.cs
+++ b/Helpers/Registry.cs
@@ -33,15 +33,12 @@ public RegistryMonitor(string registryKeyPath, TitleBarService service)
_monitorThread = new Thread(MonitorRegistry) { IsBackground = true };
}
- public void Start()
- {
- _monitorThread.Start();
- }
+ public void Start() => _monitorThread.Start();
public void Stop()
{
_running = false;
- _changeEvent.Set();
+ _ = _changeEvent.Set();
_monitorThread.Join();
}
@@ -63,7 +60,7 @@ public void MonitorRegistry()
serv.CheckFocus();
}
- _changeEvent.WaitOne();
+ _ = _changeEvent.WaitOne();
}
}
diff --git a/Helpers/SettingsHelper.cs b/Helpers/SettingsHelper.cs
index e4070d4..216463f 100644
--- a/Helpers/SettingsHelper.cs
+++ b/Helpers/SettingsHelper.cs
@@ -1,6 +1,3 @@
-using System;
-using Windows.Storage;
-
namespace Rebound.Helpers;
public static class SettingsHelper
diff --git a/Helpers/SingleInstanceHelper.cs b/Helpers/SingleInstanceHelper.cs
index 667b4e9..2b581f8 100644
--- a/Helpers/SingleInstanceHelper.cs
+++ b/Helpers/SingleInstanceHelper.cs
@@ -7,144 +7,147 @@
#nullable enable
-namespace Rebound.Helpers
+namespace Rebound.Helpers;
+
+public class SingleInstanceLaunchEventArgs(string arguments, bool isFirstLaunch) : EventArgs
{
- public class SingleInstanceLaunchEventArgs(string arguments, bool isFirstLaunch) : EventArgs
- {
- public string Arguments { get; private set; } = arguments;
- public bool IsFirstLaunch { get; private set; } = isFirstLaunch;
- }
+ public string Arguments { get; private set; } = arguments;
+ public bool IsFirstLaunch { get; private set; } = isFirstLaunch;
+}
- public sealed partial class SingleInstanceDesktopApp(string appId) : IDisposable
- {
- private readonly string _mutexName = "MUTEX_" + appId;
- private readonly string _pipeName = "PIPE_" + appId;
- private readonly object _namedPiperServerThreadLock = new();
+public sealed partial class SingleInstanceDesktopApp(string appId) : IDisposable
+{
+ private readonly string _mutexName = "MUTEX_" + appId;
+ private readonly string _pipeName = "PIPE_" + appId;
+ private readonly object _namedPiperServerThreadLock = new();
- private bool _isDisposed = false;
- private bool _isFirstInstance;
+ private bool _isDisposed = false;
+ private bool _isFirstInstance;
- private Mutex? _mutexApplication;
- private NamedPipeServerStream? _namedPipeServerStream;
+ private Mutex? _mutexApplication;
+ private NamedPipeServerStream? _namedPipeServerStream;
- public event EventHandler? Launched;
+ public event EventHandler? Launched;
- public void Launch(string arguments)
+ public void Launch(string arguments)
+ {
+ if (string.IsNullOrEmpty(arguments))
{
- if (string.IsNullOrEmpty(arguments))
+ // The arguments from LaunchActivatedEventArgs can be empty, when
+ // the user specified arguments (e.g. when using an execution alias). For this reason we
+ // alternatively check for arguments using a different API.
+ var argList = Environment.GetCommandLineArgs();
+ if (argList.Length > 1)
{
- // The arguments from LaunchActivatedEventArgs can be empty, when
- // the user specified arguments (e.g. when using an execution alias). For this reason we
- // alternatively check for arguments using a different API.
- var argList = Environment.GetCommandLineArgs();
- if (argList.Length > 1)
- {
- arguments = string.Join(' ', argList.Skip(1));
- }
+ arguments = string.Join(' ', argList.Skip(1));
}
+ }
- if (IsFirstApplicationInstance())
- {
- CreateNamedPipeServer();
- Launched?.Invoke(this, new SingleInstanceLaunchEventArgs(arguments, isFirstLaunch: true));
- }
- else
- {
- SendArgumentsToRunningInstance(arguments);
+ if (IsFirstApplicationInstance())
+ {
+ CreateNamedPipeServer();
+ Launched?.Invoke(this, new SingleInstanceLaunchEventArgs(arguments, isFirstLaunch: true));
+ }
+ else
+ {
+ SendArgumentsToRunningInstance(arguments);
- Process.GetCurrentProcess().Kill();
- // Note: needed to kill the process in WinAppSDK 1.0, since Application.Current.Exit() does not work there.
- // OR: Application.Current.Exit();
- }
+ Process.GetCurrentProcess().Kill();
+ // Note: needed to kill the process in WinAppSDK 1.0, since Application.Current.Exit() does not work there.
+ // OR: Application.Current.Exit();
}
+ }
- public void Dispose()
+ public void Dispose()
+ {
+ if (_isDisposed)
{
- if (_isDisposed)
- return;
+ return;
+ }
- _isDisposed = true;
+ _isDisposed = true;
- _namedPipeServerStream?.Dispose();
- _mutexApplication?.Dispose();
- }
+ _namedPipeServerStream?.Dispose();
+ _mutexApplication?.Dispose();
+ }
- private bool IsFirstApplicationInstance()
- {
- // Allow for multiple runs but only try and get the mutex once
- _mutexApplication ??= new Mutex(true, _mutexName, out _isFirstInstance);
+ private bool IsFirstApplicationInstance()
+ {
+ // Allow for multiple runs but only try and get the mutex once
+ _mutexApplication ??= new Mutex(true, _mutexName, out _isFirstInstance);
- return _isFirstInstance;
- }
+ return _isFirstInstance;
+ }
- ///
- /// Starts a new pipe server if one isn't already active.
- ///
- private void CreateNamedPipeServer()
+ ///
+ /// Starts a new pipe server if one isn't already active.
+ ///
+ private void CreateNamedPipeServer()
+ {
+ _namedPipeServerStream = new NamedPipeServerStream(
+ _pipeName, PipeDirection.In,
+ maxNumberOfServerInstances: 1,
+ PipeTransmissionMode.Byte,
+ PipeOptions.Asynchronous,
+ inBufferSize: 0,
+ outBufferSize: 0);
+
+ _ = _namedPipeServerStream.BeginWaitForConnection(OnNamedPipeServerConnected, _namedPipeServerStream);
+ }
+
+ private void SendArgumentsToRunningInstance(string arguments)
+ {
+ try
{
- _namedPipeServerStream = new NamedPipeServerStream(
- _pipeName, PipeDirection.In,
- maxNumberOfServerInstances: 1,
- PipeTransmissionMode.Byte,
- PipeOptions.Asynchronous,
- inBufferSize: 0,
- outBufferSize: 0);
-
- _namedPipeServerStream.BeginWaitForConnection(OnNamedPipeServerConnected, _namedPipeServerStream);
+ using var namedPipeClientStream = new NamedPipeClientStream(".", _pipeName, PipeDirection.Out);
+ namedPipeClientStream.Connect(3000); // Maximum wait 3 seconds
+ using var sw = new StreamWriter(namedPipeClientStream);
+ sw.Write(arguments);
+ sw.Flush();
}
-
- private void SendArgumentsToRunningInstance(string arguments)
+ catch (Exception)
{
- try
- {
- using var namedPipeClientStream = new NamedPipeClientStream(".", _pipeName, PipeDirection.Out);
- namedPipeClientStream.Connect(3000); // Maximum wait 3 seconds
- using var sw = new StreamWriter(namedPipeClientStream);
- sw.Write(arguments);
- sw.Flush();
- }
- catch (Exception)
- {
- // Error connecting or sending
- }
+ // Error connecting or sending
}
+ }
- private void OnNamedPipeServerConnected(IAsyncResult asyncResult)
+ private void OnNamedPipeServerConnected(IAsyncResult asyncResult)
+ {
+ try
{
- try
+ if (_namedPipeServerStream == null)
{
- if (_namedPipeServerStream == null)
- return;
-
- _namedPipeServerStream.EndWaitForConnection(asyncResult);
-
- // Read the arguments from the pipe
- lock (_namedPiperServerThreadLock)
- {
- using var sr = new StreamReader(_namedPipeServerStream);
- var args = sr.ReadToEnd();
- Launched?.Invoke(this, new SingleInstanceLaunchEventArgs(args, isFirstLaunch: false));
- }
- }
- catch (ObjectDisposedException)
- {
- // EndWaitForConnection will throw when the pipe closes before there is a connection.
- // In that case, we don't create more pipes and just return.
- // This will happen when the app is closed and therefor the pipe is closed as well.
return;
}
- catch (Exception)
- {
- // ignored
- }
- finally
+
+ _namedPipeServerStream.EndWaitForConnection(asyncResult);
+
+ // Read the arguments from the pipe
+ lock (_namedPiperServerThreadLock)
{
- // Close the original pipe (we will create a new one each time)
- _namedPipeServerStream?.Dispose();
+ using var sr = new StreamReader(_namedPipeServerStream);
+ var args = sr.ReadToEnd();
+ Launched?.Invoke(this, new SingleInstanceLaunchEventArgs(args, isFirstLaunch: false));
}
-
- // Create a new pipe for next connection
- CreateNamedPipeServer();
}
+ catch (ObjectDisposedException)
+ {
+ // EndWaitForConnection will throw when the pipe closes before there is a connection.
+ // In that case, we don't create more pipes and just return.
+ // This will happen when the app is closed and therefor the pipe is closed as well.
+ return;
+ }
+ catch (Exception)
+ {
+ // ignored
+ }
+ finally
+ {
+ // Close the original pipe (we will create a new one each time)
+ _namedPipeServerStream?.Dispose();
+ }
+
+ // Create a new pipe for next connection
+ CreateNamedPipeServer();
}
}
diff --git a/Helpers/TitleBarService.cs b/Helpers/TitleBarService.cs
index 113eee2..2754115 100644
--- a/Helpers/TitleBarService.cs
+++ b/Helpers/TitleBarService.cs
@@ -1,15 +1,14 @@
-using Microsoft.UI.Xaml.Media.Imaging;
-using System.Threading.Tasks;
using System;
-using WinUIEx;
-using WinUIEx.Messaging;
-using Microsoft.UI.Xaml.Media;
-using Microsoft.UI.Xaml;
+using System.Threading.Tasks;
using Microsoft.UI;
-using Microsoft.UI.Xaml.Controls;
using Microsoft.UI.Windowing;
-using Windows.Graphics;
+using Microsoft.UI.Xaml;
+using Microsoft.UI.Xaml.Controls;
using Microsoft.UI.Xaml.Input;
+using Microsoft.UI.Xaml.Media;
+using Microsoft.UI.Xaml.Media.Imaging;
+using WinUIEx;
+using WinUIEx.Messaging;
namespace Rebound.Helpers;
@@ -25,9 +24,15 @@ public class TitleBarService
private readonly FontIcon MaxResGlyph;
private readonly FrameworkElement Content;
- private WindowMessageMonitor MessageMonitor { get; set; }
+ private WindowMessageMonitor MessageMonitor
+ {
+ get; set;
+ }
private bool IsWindowFocused { get; set; } = false;
- private SolidColorBrush ButtonBrush { get; set; }
+ private SolidColorBrush ButtonBrush
+ {
+ get; set;
+ }
private double AdditionalHeight = 0;
@@ -81,10 +86,7 @@ public async void CheckWindow()
}
}
- private void CurrentWindow_WindowStateChanged(object sender, WindowState e)
- {
- CheckMaximization();
- }
+ private void CurrentWindow_WindowStateChanged(object sender, WindowState e) => CheckMaximization();
private void PointerMoved(object sender, PointerRoutedEventArgs e)
{
@@ -123,14 +125,7 @@ private void PointerExited(object sender, PointerRoutedEventArgs e)
}
}
- public static bool IsInRect(double x, double xMin, double xMax, double y, double yMin, double yMax)
- {
- if (xMin <= x && x <= xMax && yMin <= y && y <= yMax)
- {
- return true;
- }
- return false;
- }
+ public static bool IsInRect(double x, double xMin, double xMax, double y, double yMin, double yMax) => xMin <= x && x <= xMax && yMin <= y && y <= yMax;
private async void Rehook()
{
@@ -149,10 +144,7 @@ public void SetWindowIcon(string path)
CurrentWindow.SetIcon($"{AppContext.BaseDirectory}\\{path}");
}
- public WindowEx GetWindow()
- {
- return CurrentWindow;
- }
+ public WindowEx GetWindow() => CurrentWindow;
public static bool IsAccentColorEnabledForTitleBars()
{
@@ -222,7 +214,7 @@ private async void Event(object sender, WindowMessageEventArgs e)
double minButtonLeftPos = 0;
double maxButtonLeftPos = 0;
- double closeButtonLeftPos = 0;
+ double closeButtonLeftPos = 0;
double buttonsMinY = 0;
double buttonsMaxY = 0;
@@ -245,49 +237,49 @@ private async void Event(object sender, WindowMessageEventArgs e)
minButtonLeftPos = (Minimize.Width + MaxRes.Width + Close.Width) * Display.Scale(CurrentWindow);
maxButtonLeftPos = (MaxRes.Width + Close.Width) * Display.Scale(CurrentWindow);
closeButtonLeftPos = Close.Width * Display.Scale(CurrentWindow);
- buttonsMinY = Close.Margin.Top * Display.Scale(CurrentWindow) + 2;
+ buttonsMinY = (Close.Margin.Top * Display.Scale(CurrentWindow)) + 2;
buttonsMaxY = (Close.Height + Close.Margin.Top) * Display.Scale(CurrentWindow);
// Gets the X positions from: Window X + Window border + (Window size +/- button size)
xMinimizeMin =
CurrentWindow.AppWindow.Position.X +
- 7 * Display.Scale(CurrentWindow) +
- (CurrentWindow.Bounds.Width * Display.Scale(CurrentWindow) - minButtonLeftPos);
+ (7 * Display.Scale(CurrentWindow)) +
+ ((CurrentWindow.Bounds.Width * Display.Scale(CurrentWindow)) - minButtonLeftPos);
xMinimizeMax =
CurrentWindow.AppWindow.Position.X +
- 7 * Display.Scale(CurrentWindow) +
- (CurrentWindow.Bounds.Width * Display.Scale(CurrentWindow) - maxButtonLeftPos);
+ (7 * Display.Scale(CurrentWindow)) +
+ ((CurrentWindow.Bounds.Width * Display.Scale(CurrentWindow)) - maxButtonLeftPos);
xMaximizeMin =
CurrentWindow.AppWindow.Position.X +
- 7 * Display.Scale(CurrentWindow) +
- (CurrentWindow.Bounds.Width * Display.Scale(CurrentWindow) - maxButtonLeftPos);
+ (7 * Display.Scale(CurrentWindow)) +
+ ((CurrentWindow.Bounds.Width * Display.Scale(CurrentWindow)) - maxButtonLeftPos);
xMaximizeMax =
CurrentWindow.AppWindow.Position.X +
- 7 * Display.Scale(CurrentWindow) +
- (CurrentWindow.Bounds.Width * Display.Scale(CurrentWindow) - closeButtonLeftPos);
+ (7 * Display.Scale(CurrentWindow)) +
+ ((CurrentWindow.Bounds.Width * Display.Scale(CurrentWindow)) - closeButtonLeftPos);
xCloseMin =
CurrentWindow.AppWindow.Position.X +
- 7 * Display.Scale(CurrentWindow) +
- (CurrentWindow.Bounds.Width * Display.Scale(CurrentWindow) - closeButtonLeftPos);
+ (7 * Display.Scale(CurrentWindow)) +
+ ((CurrentWindow.Bounds.Width * Display.Scale(CurrentWindow)) - closeButtonLeftPos);
xCloseMax =
CurrentWindow.AppWindow.Position.X +
- 7 * Display.Scale(CurrentWindow) +
- CurrentWindow.Bounds.Width * Display.Scale(CurrentWindow);
+ (7 * Display.Scale(CurrentWindow)) +
+ (CurrentWindow.Bounds.Width * Display.Scale(CurrentWindow));
// Gets the Y positions from: Window Y + Window border + (Window size +/- button size)
yMin =
CurrentWindow.AppWindow.Position.Y +
- AdditionalHeight * Display.Scale(CurrentWindow) +
+ (AdditionalHeight * Display.Scale(CurrentWindow)) +
buttonsMinY;
yMax =
CurrentWindow.AppWindow.Position.Y +
- AdditionalHeight * Display.Scale(CurrentWindow) +
+ (AdditionalHeight * Display.Scale(CurrentWindow)) +
buttonsMaxY;
}
}
@@ -322,20 +314,13 @@ private async void Event(object sender, WindowMessageEventArgs e)
{
e.Handled = true;
e.Result = new IntPtr(8);
- if (CurrentCaption == SelectedCaptionButton.Minimize)
- {
- VisualStateManager.GoToState(Minimize, "Pressed", true);
- }
- else if (CurrentCaption == SelectedCaptionButton.None)
- {
- VisualStateManager.GoToState(Minimize, "PointerOver", true);
- }
- else
- {
- VisualStateManager.GoToState(Minimize, "Normal", true);
- }
- VisualStateManager.GoToState(MaxRes, "Normal", true);
- VisualStateManager.GoToState(Close, "Normal", true);
+ _ = CurrentCaption == SelectedCaptionButton.Minimize
+ ? VisualStateManager.GoToState(Minimize, "Pressed", true)
+ : CurrentCaption == SelectedCaptionButton.None
+ ? VisualStateManager.GoToState(Minimize, "PointerOver", true)
+ : VisualStateManager.GoToState(Minimize, "Normal", true);
+ _ = VisualStateManager.GoToState(MaxRes, "Normal", true);
+ _ = VisualStateManager.GoToState(Close, "Normal", true);
await Task.Delay(1000);
e.Handled = false;
}
@@ -345,20 +330,13 @@ private async void Event(object sender, WindowMessageEventArgs e)
{
e.Handled = true;
e.Result = new IntPtr(9);
- VisualStateManager.GoToState(Minimize, "Normal", true);
- if (CurrentCaption == SelectedCaptionButton.Maximize)
- {
- VisualStateManager.GoToState(MaxRes, "Pressed", true);
- }
- else if (CurrentCaption == SelectedCaptionButton.None)
- {
- VisualStateManager.GoToState(MaxRes, "PointerOver", true);
- }
- else
- {
- VisualStateManager.GoToState(MaxRes, "Normal", true);
- }
- VisualStateManager.GoToState(Close, "Normal", true);
+ _ = VisualStateManager.GoToState(Minimize, "Normal", true);
+ _ = CurrentCaption == SelectedCaptionButton.Maximize
+ ? VisualStateManager.GoToState(MaxRes, "Pressed", true)
+ : CurrentCaption == SelectedCaptionButton.None
+ ? VisualStateManager.GoToState(MaxRes, "PointerOver", true)
+ : VisualStateManager.GoToState(MaxRes, "Normal", true);
+ _ = VisualStateManager.GoToState(Close, "Normal", true);
await Task.Delay(1000);
e.Handled = false;
}
@@ -368,20 +346,13 @@ private async void Event(object sender, WindowMessageEventArgs e)
{
e.Handled = true;
e.Result = new IntPtr(20);
- VisualStateManager.GoToState(Minimize, "Normal", true);
- VisualStateManager.GoToState(MaxRes, "Normal", true);
- if (CurrentCaption == SelectedCaptionButton.Close)
- {
- VisualStateManager.GoToState(Close, "Pressed", true);
- }
- else if (CurrentCaption == SelectedCaptionButton.None)
- {
- VisualStateManager.GoToState(Close, "PointerOver", true);
- }
- else
- {
- VisualStateManager.GoToState(Close, "Normal", true);
- }
+ _ = VisualStateManager.GoToState(Minimize, "Normal", true);
+ _ = VisualStateManager.GoToState(MaxRes, "Normal", true);
+ _ = CurrentCaption == SelectedCaptionButton.Close
+ ? VisualStateManager.GoToState(Close, "Pressed", true)
+ : CurrentCaption == SelectedCaptionButton.None
+ ? VisualStateManager.GoToState(Close, "PointerOver", true)
+ : VisualStateManager.GoToState(Close, "Normal", true);
await Task.Delay(1000);
e.Handled = false;
}
@@ -391,9 +362,9 @@ private async void Event(object sender, WindowMessageEventArgs e)
{
e.Handled = true;
e.Result = new IntPtr(1);
- VisualStateManager.GoToState(Minimize, "Normal", true);
- VisualStateManager.GoToState(MaxRes, "Normal", true);
- VisualStateManager.GoToState(Close, "Normal", true);
+ _ = VisualStateManager.GoToState(Minimize, "Normal", true);
+ _ = VisualStateManager.GoToState(MaxRes, "Normal", true);
+ _ = VisualStateManager.GoToState(Close, "Normal", true);
e.Handled = false;
}
@@ -409,36 +380,36 @@ private async void Event(object sender, WindowMessageEventArgs e)
if (IsInRect(x, xMinimizeMin, xMinimizeMax, y, yMin, yMax))
{
CurrentCaption = SelectedCaptionButton.Minimize;
- VisualStateManager.GoToState(Minimize, "Pressed", true);
- VisualStateManager.GoToState(MaxRes, "Normal", true);
- VisualStateManager.GoToState(Close, "Normal", true);
+ _ = VisualStateManager.GoToState(Minimize, "Pressed", true);
+ _ = VisualStateManager.GoToState(MaxRes, "Normal", true);
+ _ = VisualStateManager.GoToState(Close, "Normal", true);
}
// Maximize Button
else if (IsInRect(x, xMaximizeMin, xMaximizeMax, y, yMin, yMax))
{
CurrentCaption = SelectedCaptionButton.Maximize;
- VisualStateManager.GoToState(Minimize, "Normal", true);
- VisualStateManager.GoToState(MaxRes, "Pressed", true);
- VisualStateManager.GoToState(Close, "Normal", true);
+ _ = VisualStateManager.GoToState(Minimize, "Normal", true);
+ _ = VisualStateManager.GoToState(MaxRes, "Pressed", true);
+ _ = VisualStateManager.GoToState(Close, "Normal", true);
}
// Close Button
else if (IsInRect(x, xCloseMin, xCloseMax, y, yMin, yMax))
{
CurrentCaption = SelectedCaptionButton.Close;
- VisualStateManager.GoToState(Minimize, "Normal", true);
- VisualStateManager.GoToState(MaxRes, "Normal", true);
- VisualStateManager.GoToState(Close, "Pressed", true);
+ _ = VisualStateManager.GoToState(Minimize, "Normal", true);
+ _ = VisualStateManager.GoToState(MaxRes, "Normal", true);
+ _ = VisualStateManager.GoToState(Close, "Pressed", true);
}
// Title bar drag area
else
{
CurrentCaption = SelectedCaptionButton.None;
- VisualStateManager.GoToState(Minimize, "Normal", true);
- VisualStateManager.GoToState(MaxRes, "Normal", true);
- VisualStateManager.GoToState(Close, "Normal", true);
+ _ = VisualStateManager.GoToState(Minimize, "Normal", true);
+ _ = VisualStateManager.GoToState(MaxRes, "Normal", true);
+ _ = VisualStateManager.GoToState(Close, "Normal", true);
}
break;
@@ -455,9 +426,9 @@ private async void Event(object sender, WindowMessageEventArgs e)
if (CurrentCaption == SelectedCaptionButton.Minimize)
{
CurrentWindow.Minimize();
- VisualStateManager.GoToState(Minimize, "Normal", true);
- VisualStateManager.GoToState(MaxRes, "Normal", true);
- VisualStateManager.GoToState(Close, "Normal", true);
+ _ = VisualStateManager.GoToState(Minimize, "Normal", true);
+ _ = VisualStateManager.GoToState(MaxRes, "Normal", true);
+ _ = VisualStateManager.GoToState(Close, "Normal", true);
}
}
@@ -496,9 +467,9 @@ private async void Event(object sender, WindowMessageEventArgs e)
e.Handled = true;
e.Result = new IntPtr(1);
e.Handled = false;
- VisualStateManager.GoToState(Minimize, "Normal", true);
- VisualStateManager.GoToState(MaxRes, "Normal", true);
- VisualStateManager.GoToState(Close, "Normal", true);
+ _ = VisualStateManager.GoToState(Minimize, "Normal", true);
+ _ = VisualStateManager.GoToState(MaxRes, "Normal", true);
+ _ = VisualStateManager.GoToState(Close, "Normal", true);
break;
}
default:
@@ -535,7 +506,7 @@ public async void CheckMaximization()
{
MaxResGlyph.Glyph = "";
await Task.Delay(10);
- VisualStateManager.GoToState(MaxRes, "Normal", true);
+ _ = VisualStateManager.GoToState(MaxRes, "Normal", true);
AdditionalHeight = 0;
return;
}
@@ -543,7 +514,7 @@ public async void CheckMaximization()
{
MaxResGlyph.Glyph = "";
await Task.Delay(10);
- VisualStateManager.GoToState(MaxRes, "Normal", true);
+ _ = VisualStateManager.GoToState(MaxRes, "Normal", true);
AdditionalHeight = 6;
return;
}
@@ -552,7 +523,7 @@ public async void CheckMaximization()
{
MaxResGlyph.Glyph = "";
await Task.Delay(10);
- VisualStateManager.GoToState(MaxRes, "Normal", true);
+ _ = VisualStateManager.GoToState(MaxRes, "Normal", true);
return;
}
}
@@ -570,7 +541,7 @@ public async void LoadBounds()
var rect = new RectInt32(0, 0, (int)(CurrentWindow.Bounds.Width * Display.Scale(CurrentWindow)), (int)(31 * Display.Scale(CurrentWindow)));
- RectInt32[] rects = [ rect ];
+ RectInt32[] rects = [rect];
titleBar.SetDragRectangles(rects);
}
diff --git a/Helpers/Win32.cs b/Helpers/Win32.cs
index b8b9cac..d3c4aa9 100644
--- a/Helpers/Win32.cs
+++ b/Helpers/Win32.cs
@@ -4,9 +4,6 @@
using Microsoft.UI.Xaml;
using WinUIEx;
-#pragma warning disable SYSLIB1054 // Use 'LibraryImportAttribute' instead of 'DllImportAttribute' to generate P/Invoke marshalling code at compile time
-#pragma warning disable CA1401 // P/Invokes should not be visible
-
namespace Rebound.Helpers;
public static class Win32
@@ -70,13 +67,7 @@ async void CheckTheme()
}
}
- public static int GET_X_LPARAM(IntPtr lParam)
- {
- return unchecked((short)(long)lParam);
- }
+ public static int GET_X_LPARAM(IntPtr lParam) => unchecked((short)(long)lParam);
- public static int GET_Y_LPARAM(IntPtr lParam)
- {
- return unchecked((short)((long)lParam >> 16));
- }
+ public static int GET_Y_LPARAM(IntPtr lParam) => unchecked((short)((long)lParam >> 16));
}
diff --git a/Installer/App.xaml.cs b/Installer/App.xaml.cs
index f81d675..64f274f 100644
--- a/Installer/App.xaml.cs
+++ b/Installer/App.xaml.cs
@@ -1,50 +1,33 @@
using Microsoft.UI.Xaml;
-using Microsoft.UI.Xaml.Controls;
-using Microsoft.UI.Xaml.Controls.Primitives;
-using Microsoft.UI.Xaml.Data;
-using Microsoft.UI.Xaml.Input;
-using Microsoft.UI.Xaml.Media;
-using Microsoft.UI.Xaml.Navigation;
-using Microsoft.UI.Xaml.Shapes;
-using System;
-using System.Collections.Generic;
-using System.IO;
-using System.Linq;
-using System.Runtime.InteropServices.WindowsRuntime;
-using Windows.ApplicationModel;
-using Windows.ApplicationModel.Activation;
-using Windows.Foundation;
-using Windows.Foundation.Collections;
// To learn more about WinUI, the WinUI project structure,
// and more about our project templates, see: http://aka.ms/winui-project-info.
-namespace ReboundHubInstaller
+namespace ReboundHubInstaller;
+
+///
+/// Provides application-specific behavior to supplement the default Application class.
+///
+public partial class App : Application
{
///
- /// Provides application-specific behavior to supplement the default Application class.
+ /// Initializes the singleton application object. This is the first line of authored code
+ /// executed, and as such is the logical equivalent of main() or WinMain().
///
- public partial class App : Application
+ public App()
{
- ///
- /// Initializes the singleton application object. This is the first line of authored code
- /// executed, and as such is the logical equivalent of main() or WinMain().
- ///
- public App()
- {
- this.InitializeComponent();
- }
-
- ///
- /// Invoked when the application is launched.
- ///
- /// Details about the launch request and process.
- protected override void OnLaunched(Microsoft.UI.Xaml.LaunchActivatedEventArgs args)
- {
- m_window = new MainWindow();
- m_window.Activate();
- }
+ InitializeComponent();
+ }
- private Window m_window;
+ ///
+ /// Invoked when the application is launched.
+ ///
+ /// Details about the launch request and process.
+ protected override void OnLaunched(Microsoft.UI.Xaml.LaunchActivatedEventArgs args)
+ {
+ m_window = new MainWindow();
+ m_window.Activate();
}
+
+ private Window m_window;
}
diff --git a/Installer/MainWindow.xaml.cs b/Installer/MainWindow.xaml.cs
index 2c86d71..855da44 100644
--- a/Installer/MainWindow.xaml.cs
+++ b/Installer/MainWindow.xaml.cs
@@ -1,247 +1,241 @@
-using Microsoft.UI.Xaml;
-using Microsoft.UI.Xaml.Media;
using System;
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
using System.Security.Cryptography.X509Certificates;
using System.Threading.Tasks;
+using Microsoft.UI.Xaml;
+using Microsoft.UI.Xaml.Media;
using WinUIEx;
-namespace ReboundHubInstaller
+namespace ReboundHubInstaller;
+
+public sealed partial class MainWindow : WindowEx
{
- public sealed partial class MainWindow : WindowEx
+ public MainWindow()
{
- public MainWindow()
- {
- this.InitializeComponent();
- this.SystemBackdrop = new MicaBackdrop();
- this.SetIcon($"{AppContext.BaseDirectory}\\Assets\\ReboundHub.ico");
- this.Title = $"Install Rebound Hub";
- this.SetWindowSize(475, 335);
- this.CenterOnScreen();
- this.IsMaximizable = false;
- this.IsResizable = false;
- SetDarkMode(this);
- }
+ InitializeComponent();
+ SystemBackdrop = new MicaBackdrop();
+ this.SetIcon($"{AppContext.BaseDirectory}\\Assets\\ReboundHub.ico");
+ Title = $"Install Rebound Hub";
+ this.SetWindowSize(475, 335);
+ this.CenterOnScreen();
+ IsMaximizable = false;
+ IsResizable = false;
+ SetDarkMode(this);
+ }
- // Get the directory of the current process
- string GetCurrentProcessDirectory()
- {
- // Get the current process
- Process currentProcess = Process.GetCurrentProcess();
+ // Get the directory of the current process
+ private string GetCurrentProcessDirectory()
+ {
+ // Get the current process
+ var currentProcess = Process.GetCurrentProcess();
- // Get the path of the executable file
- string executablePath = currentProcess.MainModule.FileName;
+ // Get the path of the executable file
+ var executablePath = currentProcess.MainModule.FileName;
- // Get the directory of the executable file
- string directoryPath = Path.GetDirectoryName(executablePath);
+ // Get the directory of the executable file
+ var directoryPath = Path.GetDirectoryName(executablePath);
- return directoryPath;
- }
+ return directoryPath;
+ }
- private void WindowEx_Closed(object sender, WindowEventArgs args)
- {
- Process.GetCurrentProcess().Kill();
- }
+ private void WindowEx_Closed(object sender, WindowEventArgs args) => Process.GetCurrentProcess().Kill();
- [DllImport("dwmapi.dll", SetLastError = true)]
- public static extern int DwmSetWindowAttribute(IntPtr hwnd, int dwAttribute, ref int pvAttribute, int cbAttribute);
+ [DllImport("dwmapi.dll", SetLastError = true)]
+ public static extern int DwmSetWindowAttribute(IntPtr hwnd, int dwAttribute, ref int pvAttribute, int cbAttribute);
- public static void SetDarkMode(WindowEx window)
+ public static void SetDarkMode(WindowEx window)
+ {
+ var i = 1;
+ if (App.Current.RequestedTheme == Microsoft.UI.Xaml.ApplicationTheme.Light)
{
- int i = 1;
- if (App.Current.RequestedTheme == Microsoft.UI.Xaml.ApplicationTheme.Light)
- {
- i = 0;
- }
- IntPtr hWnd = WinRT.Interop.WindowNative.GetWindowHandle(window);
- DwmSetWindowAttribute(hWnd, 20, ref i, sizeof(int));
- CheckTheme();
- async void CheckTheme()
- {
- await Task.Delay(100);
- try
- {
- int i = 1;
- if (App.Current.RequestedTheme == Microsoft.UI.Xaml.ApplicationTheme.Light)
- {
- i = 0;
- }
- IntPtr hWnd = WinRT.Interop.WindowNative.GetWindowHandle(window);
- DwmSetWindowAttribute(hWnd, 20, ref i, sizeof(int));
- CheckTheme();
- }
- catch
- {
-
- }
- }
+ i = 0;
}
-
- private async void Install_Click(object sender, RoutedEventArgs e)
+ var hWnd = WinRT.Interop.WindowNative.GetWindowHandle(window);
+ _ = DwmSetWindowAttribute(hWnd, 20, ref i, sizeof(int));
+ CheckTheme();
+ async void CheckTheme()
{
- Install.IsEnabled = false;
+ await Task.Delay(100);
try
{
- // Load the certificate from file
- X509Certificate2 certificate = new X509Certificate2($"{AppContext.BaseDirectory}\\ReboundHub.cer");
-
- // Define the store location and name
- StoreLocation storeLocation = StoreLocation.LocalMachine;
- StoreName storeName = StoreName.Root;
-
- // Open the certificate store
- using (X509Store store = new X509Store(storeName, storeLocation))
+ var i = 1;
+ if (App.Current.RequestedTheme == Microsoft.UI.Xaml.ApplicationTheme.Light)
{
- store.Open(OpenFlags.ReadWrite);
-
- // Add the certificate to the store
- store.Add(certificate);
-
- // Close the store
- store.Close();
+ i = 0;
}
- await Task.Delay(50);
- }
- catch (System.Exception ex)
- {
- await Task.Delay(50);
+ var hWnd = WinRT.Interop.WindowNative.GetWindowHandle(window);
+ _ = DwmSetWindowAttribute(hWnd, 20, ref i, sizeof(int));
+ CheckTheme();
}
- Progress.Value++;
-
- try
+ catch
{
- ProcessStartInfo startInfo = new ProcessStartInfo
- {
- FileName = $@"{AppContext.BaseDirectory}\VCRedistx64.exe",
- Arguments = "/quiet /norestart", // Modify the arguments as needed
- UseShellExecute = false,
- CreateNoWindow = true,
- RedirectStandardOutput = true,
- RedirectStandardError = true
- };
-
- using (Process process = new Process())
- {
- process.StartInfo = startInfo;
- process.Start();
- // Optionally capture output or error messages
- string output4 = await process.StandardOutput.ReadToEndAsync();
- string error4 = await process.StandardError.ReadToEndAsync();
+ }
+ }
+ }
- // Wait for the process to exit
- await process.WaitForExitAsync();
+ private async void Install_Click(object sender, RoutedEventArgs e)
+ {
+ Install.IsEnabled = false;
+ try
+ {
+ // Load the certificate from file
+ var certificate = new X509Certificate2($"{AppContext.BaseDirectory}\\ReboundHub.cer");
- if (process.ExitCode != 0)
- {
- throw new System.Exception($"Installer exited with code {process.ExitCode}. Error: {error4}");
- }
+ // Define the store location and name
+ var storeLocation = StoreLocation.LocalMachine;
+ var storeName = StoreName.Root;
- // Optional: handle the output or error as needed
- Debug.WriteLine($"Installer output: {output4}");
- }
- }
- catch (System.Exception ex)
+ // Open the certificate store
+ using (var store = new X509Store(storeName, storeLocation))
{
- Debug.WriteLine($"Failed to install VCRUNTIME: {ex.Message}");
- // Handle exceptions as necessary, e.g., log the error or show a message to the user
- }
+ store.Open(OpenFlags.ReadWrite);
- Progress.Value++;
+ // Add the certificate to the store
+ store.Add(certificate);
- if (Directory.Exists(@"C:\Rebound11Temp") != true)
- {
- Directory.CreateDirectory(@"C:\Rebound11Temp");
+ // Close the store
+ store.Close();
}
+ await Task.Delay(50);
+ }
+ catch (System.Exception)
+ {
+ await Task.Delay(50);
+ }
+ Progress.Value++;
- File.Copy($"{AppContext.BaseDirectory}\\Microsoft.WindowsAppRuntime.1.6-experimental2.msix", @"C:\Rebound11Temp\Runtime.msix", true);
-
- // Setup the process start info
- var procFolder = new ProcessStartInfo()
+ try
+ {
+ var startInfo = new ProcessStartInfo
{
- FileName = "powershell.exe",
- Verb = "runas", // Run as administrator
+ FileName = $@"{AppContext.BaseDirectory}\VCRedistx64.exe",
+ Arguments = "/quiet /norestart", // Modify the arguments as needed
UseShellExecute = false,
- CreateNoWindow = true,// Required to redirect output
- Arguments = @$"-Command ""Add-AppxPackage -Path 'C:\Rebound11Temp\Runtime.msix'""",
+ CreateNoWindow = true,
RedirectStandardOutput = true,
RedirectStandardError = true
};
- // Start the process
- var resFolder = Process.Start(procFolder);
+ using var process = new Process();
+ process.StartInfo = startInfo;
+ _ = process.Start();
- // Read output and errors
- string output = await resFolder.StandardOutput.ReadToEndAsync();
- string error = await resFolder.StandardError.ReadToEndAsync();
+ // Optionally capture output or error messages
+ var output4 = await process.StandardOutput.ReadToEndAsync();
+ var error4 = await process.StandardError.ReadToEndAsync();
// Wait for the process to exit
- await resFolder.WaitForExitAsync();
- Progress.Value++;
+ await process.WaitForExitAsync();
- File.Delete("C:\\Rebound11Temp\\Runtime.msix");
+ if (process.ExitCode != 0)
+ {
+ throw new System.Exception($"Installer exited with code {process.ExitCode}. Error: {error4}");
+ }
- File.Copy($"{AppContext.BaseDirectory}\\ReboundHub.msix", @"C:\Rebound11Temp\ReboundHub.msix", true);
+ // Optional: handle the output or error as needed
+ Debug.WriteLine($"Installer output: {output4}");
+ }
+ catch (System.Exception ex)
+ {
+ Debug.WriteLine($"Failed to install VCRUNTIME: {ex.Message}");
+ // Handle exceptions as necessary, e.g., log the error or show a message to the user
+ }
- await Task.Delay(50);
+ Progress.Value++;
- // Setup the process start info
- var procFolder2 = new ProcessStartInfo()
- {
- FileName = "powershell.exe",
- Verb = "runas", // Run as administrator
- UseShellExecute = false,
- CreateNoWindow = true,// Required to redirect output
- Arguments = @$"-Command ""Add-AppxPackage -Path 'C:\Rebound11Temp\ReboundHub.msix'""",
- RedirectStandardOutput = true,
- RedirectStandardError = true
- };
+ if (Directory.Exists(@"C:\Rebound11Temp") != true)
+ {
+ _ = Directory.CreateDirectory(@"C:\Rebound11Temp");
+ }
- // Start the process
- var resFolder2 = Process.Start(procFolder2);
+ File.Copy($"{AppContext.BaseDirectory}\\Microsoft.WindowsAppRuntime.1.6-experimental2.msix", @"C:\Rebound11Temp\Runtime.msix", true);
- // Read output and errors
- string output2 = await resFolder2.StandardOutput.ReadToEndAsync();
- string error2 = await resFolder2.StandardError.ReadToEndAsync();
+ // Setup the process start info
+ var procFolder = new ProcessStartInfo()
+ {
+ FileName = "powershell.exe",
+ Verb = "runas", // Run as administrator
+ UseShellExecute = false,
+ CreateNoWindow = true,// Required to redirect output
+ Arguments = @$"-Command ""Add-AppxPackage -Path 'C:\Rebound11Temp\Runtime.msix'""",
+ RedirectStandardOutput = true,
+ RedirectStandardError = true
+ };
- // Wait for the process to exit
- await resFolder2.WaitForExitAsync();
- Progress.Value++;
+ // Start the process
+ var resFolder = Process.Start(procFolder);
- File.Delete("C:\\Rebound11Temp\\ReboundHub.msix");
+ // Read output and errors
+ _ = await resFolder.StandardOutput.ReadToEndAsync();
+ _ = await resFolder.StandardError.ReadToEndAsync();
- await Task.Delay(500);
+ // Wait for the process to exit
+ await resFolder.WaitForExitAsync();
+ Progress.Value++;
- // Setup the process start info
- var procFolder3 = new ProcessStartInfo()
- {
- FileName = "powershell.exe",
- Verb = "runas", // Run as administrator
- UseShellExecute = false,
- CreateNoWindow = true,// Required to redirect output
- Arguments = @"Start-Process ""shell:AppsFolder\d6ef5e04-e9da-4e22-9782-8031af8beae7_yejd587sfa94t!App""",
- RedirectStandardOutput = true,
- RedirectStandardError = true
- };
+ File.Delete("C:\\Rebound11Temp\\Runtime.msix");
- // Start the process
- var resFolder3 = Process.Start(procFolder3);
+ File.Copy($"{AppContext.BaseDirectory}\\ReboundHub.msix", @"C:\Rebound11Temp\ReboundHub.msix", true);
- // Read output and errors
- string output3 = await resFolder3.StandardOutput.ReadToEndAsync();
- string error3 = await resFolder3.StandardError.ReadToEndAsync();
+ await Task.Delay(50);
- // Wait for the process to exit
- await resFolder2.WaitForExitAsync();
+ // Setup the process start info
+ var procFolder2 = new ProcessStartInfo()
+ {
+ FileName = "powershell.exe",
+ Verb = "runas", // Run as administrator
+ UseShellExecute = false,
+ CreateNoWindow = true,// Required to redirect output
+ Arguments = @$"-Command ""Add-AppxPackage -Path 'C:\Rebound11Temp\ReboundHub.msix'""",
+ RedirectStandardOutput = true,
+ RedirectStandardError = true
+ };
- if (Directory.Exists(@"C:\Rebound11Temp") == true)
- {
- Directory.Delete(@"C:\Rebound11Temp");
- }
+ // Start the process
+ var resFolder2 = Process.Start(procFolder2);
+
+ // Read output and errors
+ _ = await resFolder2.StandardOutput.ReadToEndAsync();
+ _ = await resFolder2.StandardError.ReadToEndAsync();
+
+ // Wait for the process to exit
+ await resFolder2.WaitForExitAsync();
+ Progress.Value++;
- Close();
+ File.Delete("C:\\Rebound11Temp\\ReboundHub.msix");
+
+ await Task.Delay(500);
+
+ // Setup the process start info
+ var procFolder3 = new ProcessStartInfo()
+ {
+ FileName = "powershell.exe",
+ Verb = "runas", // Run as administrator
+ UseShellExecute = false,
+ CreateNoWindow = true,// Required to redirect output
+ Arguments = @"Start-Process ""shell:AppsFolder\d6ef5e04-e9da-4e22-9782-8031af8beae7_yejd587sfa94t!App""",
+ RedirectStandardOutput = true,
+ RedirectStandardError = true
+ };
+
+ // Start the process
+ var resFolder3 = Process.Start(procFolder3);
+
+ // Read output and errors
+ _ = await resFolder3.StandardOutput.ReadToEndAsync();
+ _ = await resFolder3.StandardError.ReadToEndAsync();
+
+ // Wait for the process to exit
+ await resFolder2.WaitForExitAsync();
+
+ if (Directory.Exists(@"C:\Rebound11Temp") == true)
+ {
+ Directory.Delete(@"C:\Rebound11Temp");
}
+
+ Close();
}
}
diff --git a/Installer/Package.appxmanifest b/Installer/Package.appxmanifest
index 5fa4d23..8a8b945 100644
--- a/Installer/Package.appxmanifest
+++ b/Installer/Package.appxmanifest
@@ -16,7 +16,7 @@
ReboundHubInstaller
- Lenovo
+ Ivirius
Assets\StoreLogo.png
diff --git a/InteractiveDialog/App.xaml.cs b/InteractiveDialog/App.xaml.cs
index 14090cf..d51677f 100644
--- a/InteractiveDialog/App.xaml.cs
+++ b/InteractiveDialog/App.xaml.cs
@@ -16,7 +16,7 @@ public partial class App : Application
public App()
{
- this.InitializeComponent();
+ InitializeComponent();
}
///
diff --git a/InteractiveDialog/MainWindow.xaml.cs b/InteractiveDialog/MainWindow.xaml.cs
index 28bc1d2..6baca77 100644
--- a/InteractiveDialog/MainWindow.xaml.cs
+++ b/InteractiveDialog/MainWindow.xaml.cs
@@ -1,6 +1,5 @@
using System;
using System.Threading.Tasks;
-using Microsoft.UI;
using Microsoft.UI.Windowing;
using Microsoft.UI.Xaml;
using Microsoft.UI.Xaml.Controls;
@@ -21,19 +20,19 @@ public sealed partial class MainWindow : Window
public void GetAppWindowAndPresenter()
{
var hWnd = WinRT.Interop.WindowNative.GetWindowHandle(this);
- WindowId wndId = Microsoft.UI.Win32Interop.GetWindowIdFromWindow(hWnd);
+ var wndId = Microsoft.UI.Win32Interop.GetWindowIdFromWindow(hWnd);
_apw = AppWindow.GetFromWindowId(wndId);
_presenter = _apw.Presenter as OverlappedPresenter ?? throw new InvalidOperationException("Presenter is not of type OverlappedPresenter");
}
public MainWindow()
{
- this.InitializeComponent();
+ InitializeComponent();
GetAppWindowAndPresenter();
_presenter.IsMaximizable = false;
_presenter.IsMinimizable = false;
- this.AppWindow.MoveAndResize(new Windows.Graphics.RectInt32(328, 198, 328, 198));
+ AppWindow.MoveAndResize(new Windows.Graphics.RectInt32(328, 198, 328, 198));
this.SetIsMinimizable(false);
this.SetIsMaximizable(false);
this.SetIsResizable(false);
@@ -44,10 +43,7 @@ public MainWindow()
window.SetTitleBar(AppTitleBar); // Set titlebar as from MainWindow.xaml
}
- private async void RootGrid_Loaded(object sender, RoutedEventArgs e)
- {
- await ShowDialog();
- }
+ private async void RootGrid_Loaded(object sender, RoutedEventArgs e) => await ShowDialog();
public async Task ShowDialog()
{
@@ -61,11 +57,8 @@ public async Task ShowDialog()
dialog.Closed += Dialog_Closed;
- await dialog.ShowAsync();
+ _ = await dialog.ShowAsync();
}
- private void Dialog_Closed(ContentDialog sender, ContentDialogClosedEventArgs args)
- {
- Application.Current.Exit();
- }
+ private void Dialog_Closed(ContentDialog sender, ContentDialogClosedEventArgs args) => Application.Current.Exit();
}
diff --git a/Rebound/App.xaml.cs b/Rebound/App.xaml.cs
index a10a52d..d8ace2d 100644
--- a/Rebound/App.xaml.cs
+++ b/Rebound/App.xaml.cs
@@ -45,7 +45,7 @@ public async Task LaunchWork()
{
if (string.Join(" ", Environment.GetCommandLineArgs().Skip(1)).Contains("CONTROL"))
{
- Process.Start(new ProcessStartInfo("control:") { UseShellExecute = true });
+ _ = Process.Start(new ProcessStartInfo("control:") { UseShellExecute = true });
MainAppWindow.Close();
}
/*if (string.Join(" ", Environment.GetCommandLineArgs().Skip(1)).Contains("UAC"))
@@ -60,27 +60,27 @@ public async Task LaunchWork()
if (string.Join(" ", Environment.GetCommandLineArgs().Skip(1)).Contains("SFC"))
{
var win = new UninstallationWindow(true);
- win.Show();
+ _ = win.Show();
await Task.Delay(10);
- win.BringToFront();
+ _ = win.BringToFront();
MainAppWindow = null;
return;
}
if (string.Join(" ", Environment.GetCommandLineArgs().Skip(1)).Contains("UNINSTALLFULL"))
{
var win = new UninstallationWindow(true);
- win.Show();
+ _ = win.Show();
await Task.Delay(10);
- win.BringToFront();
+ _ = win.BringToFront();
MainAppWindow = null;
return;
}
if (string.Join(" ", Environment.GetCommandLineArgs().Skip(1)).Contains("UNINSTALL"))
{
var win = new UninstallationWindow(false);
- win.Show();
+ _ = win.Show();
await Task.Delay(10);
- win.BringToFront();
+ _ = win.BringToFront();
MainAppWindow = null;
return;
}
@@ -98,10 +98,7 @@ private void App_UnhandledException(object sender, Microsoft.UI.Xaml.UnhandledEx
e.Handled = true; // Prevent the application from terminating
}
- protected override void OnLaunched(LaunchActivatedEventArgs args)
- {
- _singleInstanceApp?.Launch(args.Arguments);
- }
+ protected override void OnLaunched(LaunchActivatedEventArgs args) => _singleInstanceApp?.Launch(args.Arguments);
public static Window MainAppWindow;
diff --git a/Rebound/Assets/Wallpapers/WallpaperCyanDark8bit.png b/Rebound/Assets/Wallpapers/WallpaperCyanDark8bit.png
index 3874a02..1e66274 100644
Binary files a/Rebound/Assets/Wallpapers/WallpaperCyanDark8bit.png and b/Rebound/Assets/Wallpapers/WallpaperCyanDark8bit.png differ
diff --git a/Rebound/Assets/Wallpapers/WallpaperCyanLight8bit.png b/Rebound/Assets/Wallpapers/WallpaperCyanLight8bit.png
index ecefd60..200aefa 100644
Binary files a/Rebound/Assets/Wallpapers/WallpaperCyanLight8bit.png and b/Rebound/Assets/Wallpapers/WallpaperCyanLight8bit.png differ
diff --git a/Rebound/Assets/Wallpapers/WallpaperDarkBlue.png b/Rebound/Assets/Wallpapers/WallpaperDarkBlue.png
index ae0decd..b1fb0cb 100644
Binary files a/Rebound/Assets/Wallpapers/WallpaperDarkBlue.png and b/Rebound/Assets/Wallpapers/WallpaperDarkBlue.png differ
diff --git a/Rebound/Assets/Wallpapers/WallpaperDarkCrimson.png b/Rebound/Assets/Wallpapers/WallpaperDarkCrimson.png
index 0b7befd..05265e3 100644
Binary files a/Rebound/Assets/Wallpapers/WallpaperDarkCrimson.png and b/Rebound/Assets/Wallpapers/WallpaperDarkCrimson.png differ
diff --git a/Rebound/Assets/Wallpapers/WallpaperDarkPurple.png b/Rebound/Assets/Wallpapers/WallpaperDarkPurple.png
index e1db29d..f784e50 100644
Binary files a/Rebound/Assets/Wallpapers/WallpaperDarkPurple.png and b/Rebound/Assets/Wallpapers/WallpaperDarkPurple.png differ
diff --git a/Rebound/Assets/Wallpapers/WallpaperLightBlue.png b/Rebound/Assets/Wallpapers/WallpaperLightBlue.png
index e064202..309d51d 100644
Binary files a/Rebound/Assets/Wallpapers/WallpaperLightBlue.png and b/Rebound/Assets/Wallpapers/WallpaperLightBlue.png differ
diff --git a/Rebound/Assets/Wallpapers/WallpaperLightCrimson.png b/Rebound/Assets/Wallpapers/WallpaperLightCrimson.png
index 4b6f051..2bd3da8 100644
Binary files a/Rebound/Assets/Wallpapers/WallpaperLightCrimson.png and b/Rebound/Assets/Wallpapers/WallpaperLightCrimson.png differ
diff --git a/Rebound/Assets/Wallpapers/WallpaperLightPurple.png b/Rebound/Assets/Wallpapers/WallpaperLightPurple.png
index 8f10e0d..9093590 100644
Binary files a/Rebound/Assets/Wallpapers/WallpaperLightPurple.png and b/Rebound/Assets/Wallpapers/WallpaperLightPurple.png differ
diff --git a/Rebound/InstallationWindow.xaml.cs b/Rebound/InstallationWindow.xaml.cs
index d328927..35df31f 100644
--- a/Rebound/InstallationWindow.xaml.cs
+++ b/Rebound/InstallationWindow.xaml.cs
@@ -4,7 +4,6 @@
using System.Security.Cryptography.X509Certificates;
using System.Threading.Tasks;
using Microsoft.UI.Xaml;
-using Microsoft.UI.Xaml.Input;
using Rebound.WindowModels;
using WinUIEx;
using FileAttributes = System.IO.FileAttributes;
@@ -127,13 +126,13 @@ public async void Load(bool Files, bool Run, bool Defrag, bool Winver, bool UAC,
CurrentStep += 1;
- await CreateRebound11Folder();
+ _ = await CreateRebound11Folder();
#endregion Folder
#region Control Panel
- await InstallExeWithShortcut(
+ _ = await InstallExeWithShortcut(
$"{AppContext.BaseDirectory}\\Reserved\\rcontrol.exe",
$"C:\\Rebound11\\rcontrol.exe",
$"{AppContext.BaseDirectory}\\Shortcuts\\Control Panel.lnk",
@@ -151,7 +150,7 @@ await InstallExeWithShortcut(
if (Defrag == true)
{
- await InstallMsixPackage(
+ _ = await InstallMsixPackage(
$"{AppContext.BaseDirectory}\\Reserved\\Extended\\Rebound.Defrag.msix",
"C:\\Rebound11\\Rebound.Defrag.msix",
$"{AppContext.BaseDirectory}\\Reserved\\Extended\\Rebound.Defrag.cer",
@@ -170,7 +169,7 @@ await InstallMsixPackage(
if (Winver == true)
{
- await InstallMsixPackage(
+ _ = await InstallMsixPackage(
$"{AppContext.BaseDirectory}\\Reserved\\Extended\\Rebound.About.msix",
"C:\\Rebound11\\Rebound.About.msix",
$"{AppContext.BaseDirectory}\\Reserved\\Extended\\Rebound.About.cer",
@@ -189,8 +188,8 @@ await InstallMsixPackage(
if (Files == true)
{
- await InstallAppInstallerFile("Files App", "https://cdn.files.community/files/stable/Files.Package.appinstaller", "Files.exe");
- await ApplyRegFile($@"{AppContext.BaseDirectory}\AppRT\Registry\SetFilesAsDefault.reg", "Set Files as Default");
+ _ = await InstallAppInstallerFile("Files App", "https://cdn.files.community/files/stable/Files.Package.appinstaller", "Files.exe");
+ _ = await ApplyRegFile($@"{AppContext.BaseDirectory}\AppRT\Registry\SetFilesAsDefault.reg", "Set Files as Default");
}
#endregion Files
@@ -199,7 +198,7 @@ await InstallMsixPackage(
if (UAC == true)
{
- await InstallExeWithShortcut(
+ _ = await InstallExeWithShortcut(
$"{AppContext.BaseDirectory}\\Reserved\\ruacsettings.exe",
$"C:\\Rebound11\\ruacsettings.exe",
$"{AppContext.BaseDirectory}\\Shortcuts\\Change User Account Control settings.lnk",
@@ -214,7 +213,7 @@ await InstallExeWithShortcut(
if (Run == true)
{
- await InstallMsixPackage(
+ _ = await InstallMsixPackage(
$"{AppContext.BaseDirectory}\\Reserved\\Extended\\Rebound.Run.msix",
"C:\\Rebound11\\Rebound.Run.msix",
$"{AppContext.BaseDirectory}\\Reserved\\Extended\\Rebound.Run.cer",
@@ -228,7 +227,7 @@ await InstallMsixPackage(
var startupFolderPath = Environment.GetFolderPath(Environment.SpecialFolder.Startup);
- await InstallExeWithShortcut(
+ _ = await InstallExeWithShortcut(
$"{AppContext.BaseDirectory}\\Reserved\\rrunSTARTUP.exe",
$"C:\\Rebound11\\rrunSTARTUP.exe",
$"{AppContext.BaseDirectory}\\Shortcuts\\Rebound.RunStartup.lnk",
@@ -243,7 +242,7 @@ await InstallExeWithShortcut(
if (DiskCleanup == true)
{
- await InstallMsixPackage(
+ _ = await InstallMsixPackage(
$"{AppContext.BaseDirectory}\\Reserved\\Extended\\Rebound.Cleanup.msix",
"C:\\Rebound11\\Rebound.Cleanup.msix",
$"{AppContext.BaseDirectory}\\Reserved\\Extended\\Rebound.Cleanup.cer",
@@ -262,7 +261,7 @@ await InstallMsixPackage(
if (TPM == true)
{
- await InstallMsixPackage(
+ _ = await InstallMsixPackage(
$"{AppContext.BaseDirectory}\\Reserved\\Extended\\Rebound.TrustedPlatform.msix",
"C:\\Rebound11\\Rebound.TrustedPlatform.msix",
$"{AppContext.BaseDirectory}\\Reserved\\Extended\\Rebound.TrustedPlatform.cer",
@@ -281,7 +280,7 @@ await InstallMsixPackage(
if (OSK == true)
{
- await InstallExeWithShortcut(
+ _ = await InstallExeWithShortcut(
$"{AppContext.BaseDirectory}\\Reserved\\rosk.exe",
$"C:\\Rebound11\\rosk.exe",
$"{AppContext.BaseDirectory}\\Shortcuts\\On-Screen Keyboard.lnk",
@@ -330,10 +329,7 @@ public void UpdateProgress(string title)
ReboundProgress.Value = InstallProgress.Value = FinishProgress.Value = CurrentSubstep;
}
- private void Timer_Tick(object sender, object e)
- {
- TaskManager.StopTask("explorer.exe");
- }
+ private void Timer_Tick(object sender, object e) => TaskManager.StopTask("explorer.exe");
private async void Button_Click(object sender, RoutedEventArgs e)
{
@@ -621,7 +617,7 @@ public async Task ApplyRegFile(string regFilePath, string regDisplayName)
// Start the process
try
{
- process.Start();
+ _ = process.Start();
process.WaitForExit(); // Optionally wait for the process to finish
}
catch
@@ -650,7 +646,7 @@ public async Task CreateRebound11Folder()
try
{
Subtitle.Text = $@"Step {CurrentStep} of {TotalSteps}: Creating the Rebound11 folder in ""C:\"".";
- Directory.CreateDirectory("C:\\Rebound11");
+ _ = Directory.CreateDirectory("C:\\Rebound11");
}
catch
{
@@ -699,7 +695,7 @@ public async Task CreateRebound11Folder()
try
{
Subtitle.Text = $"Step {CurrentStep} of {TotalSteps}: Creating wallpapers folder...";
- Directory.CreateDirectory(@"C:\Rebound11\Wallpapers");
+ _ = Directory.CreateDirectory(@"C:\Rebound11\Wallpapers");
}
catch
{
diff --git a/Rebound/MainWindow.xaml.cs b/Rebound/MainWindow.xaml.cs
index c4ad613..0423ed8 100644
--- a/Rebound/MainWindow.xaml.cs
+++ b/Rebound/MainWindow.xaml.cs
@@ -14,7 +14,6 @@
using Microsoft.Win32;
using Rebound.Helpers;
using Rebound.Views;
-using Windows.Graphics;
using WinUIEx;
using WinUIEx.Messaging;
@@ -28,13 +27,12 @@ namespace Rebound;
public sealed partial class MainWindow : WindowEx
{
public bool AllowSizeCheck = false;
-
- bool isCrimsonUIEnabled = false;
+ private readonly bool isCrimsonUIEnabled = false;
public async void CheckWindowProperties()
{
AllowSizeCheck = false;
- this.SystemBackdrop = new MicaBackdrop()
+ SystemBackdrop = new MicaBackdrop()
{
Kind = MicaKind.Base
};
@@ -62,7 +60,11 @@ public async void CheckWindowProperties()
(double)SettingsHelper.GetSetting("Core.WindowHeight"));
}
}
- else this.CenterOnScreen();
+ else
+ {
+ this.CenterOnScreen();
+ }
+
if (SettingsHelper.GetSetting("Core.Maximized") != null)
{
if (SettingsHelper.GetSettingBool("Core.Maximized") == true)
@@ -87,11 +89,11 @@ public MainWindow()
this.InitializeComponent();
RootFrame.Navigate(typeof(ShellPage));
CheckWindowProperties();
- this.ExtendsContentIntoTitleBar = true;
- this.AppWindow.TitleBar.PreferredHeightOption = Microsoft.UI.Windowing.TitleBarHeightOption.Collapsed;
- this.AppWindow.TitleBar.ButtonHoverBackgroundColor = Windows.UI.Color.FromArgb(25, 200, 200, 200);
- this.AppWindow.TitleBar.ButtonPressedBackgroundColor = Windows.UI.Color.FromArgb(15, 200, 200, 200);
- this.AppWindow.Title = "Rebound Hub";
+ ExtendsContentIntoTitleBar = true;
+ AppWindow.TitleBar.PreferredHeightOption = Microsoft.UI.Windowing.TitleBarHeightOption.Collapsed;
+ AppWindow.TitleBar.ButtonHoverBackgroundColor = Windows.UI.Color.FromArgb(25, 200, 200, 200);
+ AppWindow.TitleBar.ButtonPressedBackgroundColor = Windows.UI.Color.FromArgb(15, 200, 200, 200);
+ AppWindow.Title = "Rebound Hub";
this.SetIcon($"{AppContext.BaseDirectory}\\Assets\\AppIcons\\Rebound.ico");
_msgMonitor ??= new WindowMessageMonitor(this);
@@ -100,7 +102,7 @@ public MainWindow()
if (isCrimsonUIEnabled == true)
{
- this.AppWindow.TitleBar.PreferredHeightOption = Microsoft.UI.Windowing.TitleBarHeightOption.Collapsed;
+ AppWindow.TitleBar.PreferredHeightOption = Microsoft.UI.Windowing.TitleBarHeightOption.Collapsed;
CrimsonUIButtons.Visibility = Visibility.Visible;
LoadBounds();
}
@@ -134,7 +136,10 @@ public async void CheckWindow()
{
try
{
- if (WindowTitle != null && this != null) WindowTitle.Text = Title;
+ if (WindowTitle != null && this != null)
+ {
+ WindowTitle.Text = Title;
+ }
}
catch
{
@@ -146,13 +151,12 @@ public async void CheckWindow()
CheckWindow();
}
- RegistryMonitor mon;
+ private readonly RegistryMonitor mon;
#region MaximizeButton
- WindowMessageMonitor _msgMonitor;
-
- double additionalHeight = 0;
+ private WindowMessageMonitor _msgMonitor;
+ private double additionalHeight = 0;
public bool isInMaxButton = false;
@@ -173,7 +177,7 @@ private void CrimsonMaxRes_PointerPressed(object sender, PointerRoutedEventArgs
isInMaxButton = false;
}
- PointerRoutedEventArgs ev;
+ private PointerRoutedEventArgs ev;
private void CrimsonMaxRes_PointerMoved(object sender, PointerRoutedEventArgs e)
{
@@ -184,19 +188,12 @@ private void CrimsonMaxRes_PointerMoved(object sender, PointerRoutedEventArgs e)
_msgMonitor.WindowMessageReceived += Event;
}
- private int GET_X_LPARAM(IntPtr lParam)
- {
- return unchecked((short)(long)lParam);
- }
-
- private int GET_Y_LPARAM(IntPtr lParam)
- {
- return unchecked((short)((long)lParam >> 16));
- }
+ private int GET_X_LPARAM(IntPtr lParam) => unchecked((short)(long)lParam);
- bool windowFocused = false;
+ private int GET_Y_LPARAM(IntPtr lParam) => unchecked((short)((long)lParam >> 16));
- SolidColorBrush buttonBrush;
+ private bool windowFocused = false;
+ private SolidColorBrush buttonBrush;
private const string RegistryKeyPath = @"Software\Microsoft\Windows\DWM";
private const string RegistryValueName = "ColorPrevalence";
@@ -217,7 +214,7 @@ private int GET_Y_LPARAM(IntPtr lParam)
private const uint REG_NOTIFY_CHANGE_LAST_SET = 0x00000004;
private const uint REG_NOTIFY_CHANGE_SECURITY = 0x00000008;
- private static ManualResetEvent _changeEvent = new(false);
+ private static readonly ManualResetEvent _changeEvent = new(false);
private static bool _running = true;
private class RegistryMonitor : IDisposable
@@ -232,15 +229,12 @@ public RegistryMonitor(string registryKeyPath)
_monitorThread = new Thread(MonitorRegistry) { IsBackground = true };
}
- public void Start()
- {
- _monitorThread.Start();
- }
+ public void Start() => _monitorThread.Start();
public void Stop()
{
_running = false;
- _changeEvent.Set();
+ _ = _changeEvent.Set();
_monitorThread.Join();
}
@@ -257,12 +251,16 @@ private void MonitorRegistry()
if (RegNotifyChangeKeyValue(_hKey, true, REG_NOTIFY_CHANGE_NAME | REG_NOTIFY_CHANGE_ATTRIBUTES | REG_NOTIFY_CHANGE_LAST_SET | REG_NOTIFY_CHANGE_SECURITY, _changeEvent.SafeWaitHandle.DangerousGetHandle(), true) == 0)
{
// Handle registry change
- if (App.MainAppWindow != null) (App.MainAppWindow as MainWindow).CheckFocus();
- _changeEvent.WaitOne();
+ if (App.MainAppWindow != null)
+ {
+ (App.MainAppWindow as MainWindow).CheckFocus();
+ }
+
+ _ = _changeEvent.WaitOne();
}
}
- RegCloseKey(_hKey);
+ _ = RegCloseKey(_hKey);
}
public void Dispose()
@@ -302,7 +300,11 @@ private void CheckFocus()
{
try
{
- if (AccentStrip != null) AccentStrip.Visibility = Visibility.Visible;
+ if (AccentStrip != null)
+ {
+ AccentStrip.Visibility = Visibility.Visible;
+ }
+
if (!windowFocused)
{
buttonBrush = new SolidColorBrush(Colors.White);
@@ -320,15 +322,14 @@ private void CheckFocus()
{
try
{
- if (AccentStrip != null) AccentStrip.Visibility = Visibility.Collapsed;
- if (!windowFocused)
- {
- buttonBrush = Application.Current.Resources["TextFillColorPrimaryBrush"] as SolidColorBrush;
- }
- else
+ if (AccentStrip != null)
{
- buttonBrush = Application.Current.Resources["TextFillColorDisabledBrush"] as SolidColorBrush;
+ AccentStrip.Visibility = Visibility.Collapsed;
}
+
+ buttonBrush = !windowFocused
+ ? Application.Current.Resources["TextFillColorPrimaryBrush"] as SolidColorBrush
+ : Application.Current.Resources["TextFillColorDisabledBrush"] as SolidColorBrush;
}
catch { }
}
@@ -360,7 +361,7 @@ public enum SelectedCaptionButton
public SelectedCaptionButton currentCaption = SelectedCaptionButton.None;
- async void Event(object sender, WinUIEx.Messaging.WindowMessageEventArgs e)
+ private async void Event(object sender, WinUIEx.Messaging.WindowMessageEventArgs e)
{
const int WM_NCLBUTTONDOWN = 0x00A1;
const int WM_NCHITTEST = 0x0084;
@@ -397,16 +398,26 @@ async void Event(object sender, WinUIEx.Messaging.WindowMessageEventArgs e)
case WM_NCHITTEST:
{
// Minimize Button
- if ((x - 7 * Scale() - this.AppWindow.Position.X) >= (this.Bounds.Width * Scale() - minButtonLeftPos) &&
- (x - 7 * Scale() - this.AppWindow.Position.X) < (this.Bounds.Width * Scale() - maxButtonLeftPos) &&
- y < this.AppWindow.Position.Y + 46 * Scale() + additionalHeight * Scale() &&
- y >= this.AppWindow.Position.Y + 1 * Scale())
+ if ((x - (7 * Scale()) - AppWindow.Position.X) >= ((Bounds.Width * Scale()) - minButtonLeftPos) &&
+ (x - (7 * Scale()) - AppWindow.Position.X) < ((Bounds.Width * Scale()) - maxButtonLeftPos) &&
+ y < AppWindow.Position.Y + (46 * Scale()) + (additionalHeight * Scale()) &&
+ y >= AppWindow.Position.Y + (1 * Scale()))
{
e.Handled = true;
e.Result = new IntPtr(8);
- if (currentCaption == SelectedCaptionButton.Minimize) VisualStateManager.GoToState(Minimize, "Pressed", true);
- else if (currentCaption == SelectedCaptionButton.None) VisualStateManager.GoToState(Minimize, "PointerOver", true);
- else VisualStateManager.GoToState(Minimize, "Normal", true);
+ if (currentCaption == SelectedCaptionButton.Minimize)
+ {
+ VisualStateManager.GoToState(Minimize, "Pressed", true);
+ }
+ else if (currentCaption == SelectedCaptionButton.None)
+ {
+ VisualStateManager.GoToState(Minimize, "PointerOver", true);
+ }
+ else
+ {
+ VisualStateManager.GoToState(Minimize, "Normal", true);
+ }
+
VisualStateManager.GoToState(CrimsonMaxRes, "Normal", true);
VisualStateManager.GoToState(Close, "Normal", true);
await Task.Delay(1000);
@@ -414,35 +425,55 @@ async void Event(object sender, WinUIEx.Messaging.WindowMessageEventArgs e)
}
// Maximize Button
- else if ((x - 7 * Scale() - this.AppWindow.Position.X) >= (this.Bounds.Width * Scale() - maxButtonLeftPos) &&
- ((x - 7 * Scale() - this.AppWindow.Position.X) < (this.Bounds.Width * Scale() - closeButtonLeftPos)) &&
- y < this.AppWindow.Position.Y + 46 * Scale() + additionalHeight * Scale() &&
- y >= this.AppWindow.Position.Y + 1 * Scale())
+ else if ((x - (7 * Scale()) - AppWindow.Position.X) >= ((Bounds.Width * Scale()) - maxButtonLeftPos) &&
+ ((x - (7 * Scale()) - AppWindow.Position.X) < ((Bounds.Width * Scale()) - closeButtonLeftPos)) &&
+ y < AppWindow.Position.Y + (46 * Scale()) + (additionalHeight * Scale()) &&
+ y >= AppWindow.Position.Y + (1 * Scale()))
{
e.Handled = true;
e.Result = new IntPtr(9);
VisualStateManager.GoToState(Minimize, "Normal", true);
- if (currentCaption == SelectedCaptionButton.Maximize) VisualStateManager.GoToState(CrimsonMaxRes, "Pressed", true);
- else if (currentCaption == SelectedCaptionButton.None) VisualStateManager.GoToState(CrimsonMaxRes, "PointerOver", true);
- else VisualStateManager.GoToState(CrimsonMaxRes, "Normal", true);
+ if (currentCaption == SelectedCaptionButton.Maximize)
+ {
+ VisualStateManager.GoToState(CrimsonMaxRes, "Pressed", true);
+ }
+ else if (currentCaption == SelectedCaptionButton.None)
+ {
+ VisualStateManager.GoToState(CrimsonMaxRes, "PointerOver", true);
+ }
+ else
+ {
+ VisualStateManager.GoToState(CrimsonMaxRes, "Normal", true);
+ }
+
VisualStateManager.GoToState(Close, "Normal", true);
await Task.Delay(1000);
e.Handled = false;
}
// Close Button
- else if ((x - 7 * Scale() - this.AppWindow.Position.X) >= (this.Bounds.Width * Scale() - closeButtonLeftPos) &&
- (x - 7 * Scale() - this.AppWindow.Position.X) < (this.Bounds.Width * Scale()) + 2 &&
- y < this.AppWindow.Position.Y + 46 * Scale() + additionalHeight * Scale() &&
- y >= this.AppWindow.Position.Y + 1 * Scale())
+ else if ((x - (7 * Scale()) - AppWindow.Position.X) >= ((Bounds.Width * Scale()) - closeButtonLeftPos) &&
+ (x - (7 * Scale()) - AppWindow.Position.X) < (Bounds.Width * Scale()) + 2 &&
+ y < AppWindow.Position.Y + (46 * Scale()) + (additionalHeight * Scale()) &&
+ y >= AppWindow.Position.Y + (1 * Scale()))
{
e.Handled = true;
e.Result = new IntPtr(20);
VisualStateManager.GoToState(Minimize, "Normal", true);
VisualStateManager.GoToState(CrimsonMaxRes, "Normal", true);
- if (currentCaption == SelectedCaptionButton.Close) VisualStateManager.GoToState(Close, "Pressed", true);
- else if (currentCaption == SelectedCaptionButton.None) VisualStateManager.GoToState(Close, "PointerOver", true);
- else VisualStateManager.GoToState(Close, "Normal", true);
+ if (currentCaption == SelectedCaptionButton.Close)
+ {
+ VisualStateManager.GoToState(Close, "Pressed", true);
+ }
+ else if (currentCaption == SelectedCaptionButton.None)
+ {
+ VisualStateManager.GoToState(Close, "PointerOver", true);
+ }
+ else
+ {
+ VisualStateManager.GoToState(Close, "Normal", true);
+ }
+
await Task.Delay(1000);
e.Handled = false;
}
@@ -467,10 +498,10 @@ async void Event(object sender, WinUIEx.Messaging.WindowMessageEventArgs e)
e.Handled = false;
// Minimize Button
- if ((x - 7 * Scale() - this.AppWindow.Position.X) >= (this.Bounds.Width * Scale() - minButtonLeftPos) &&
- (x - 7 * Scale() - this.AppWindow.Position.X) < (this.Bounds.Width * Scale() - maxButtonLeftPos) &&
- y < this.AppWindow.Position.Y + 46 * Scale() + additionalHeight * Scale() &&
- y >= this.AppWindow.Position.Y + 1 * Scale())
+ if ((x - (7 * Scale()) - AppWindow.Position.X) >= ((Bounds.Width * Scale()) - minButtonLeftPos) &&
+ (x - (7 * Scale()) - AppWindow.Position.X) < ((Bounds.Width * Scale()) - maxButtonLeftPos) &&
+ y < AppWindow.Position.Y + (46 * Scale()) + (additionalHeight * Scale()) &&
+ y >= AppWindow.Position.Y + (1 * Scale()))
{
currentCaption = SelectedCaptionButton.Minimize;
VisualStateManager.GoToState(Minimize, "Pressed", true);
@@ -479,10 +510,10 @@ async void Event(object sender, WinUIEx.Messaging.WindowMessageEventArgs e)
}
// Maximize Button
- else if ((x - 7 * Scale() - this.AppWindow.Position.X) >= (this.Bounds.Width * Scale() - maxButtonLeftPos) &&
- ((x - 7 * Scale() - this.AppWindow.Position.X) < (this.Bounds.Width * Scale() - closeButtonLeftPos)) &&
- y < this.AppWindow.Position.Y + 46 * Scale() + additionalHeight * Scale() &&
- y >= this.AppWindow.Position.Y + 1 * Scale())
+ else if ((x - (7 * Scale()) - AppWindow.Position.X) >= ((Bounds.Width * Scale()) - maxButtonLeftPos) &&
+ ((x - (7 * Scale()) - AppWindow.Position.X) < ((Bounds.Width * Scale()) - closeButtonLeftPos)) &&
+ y < AppWindow.Position.Y + (46 * Scale()) + (additionalHeight * Scale()) &&
+ y >= AppWindow.Position.Y + (1 * Scale()))
{
currentCaption = SelectedCaptionButton.Maximize;
VisualStateManager.GoToState(Minimize, "Normal", true);
@@ -491,10 +522,10 @@ async void Event(object sender, WinUIEx.Messaging.WindowMessageEventArgs e)
}
// Close Button
- else if ((x - 7 * Scale() - this.AppWindow.Position.X) >= (this.Bounds.Width * Scale() - closeButtonLeftPos) &&
- (x - 7 * Scale() - this.AppWindow.Position.X) < (this.Bounds.Width * Scale()) + 2 &&
- y < this.AppWindow.Position.Y + 46 * Scale() + additionalHeight * Scale() &&
- y >= this.AppWindow.Position.Y + 1 * Scale())
+ else if ((x - (7 * Scale()) - AppWindow.Position.X) >= ((Bounds.Width * Scale()) - closeButtonLeftPos) &&
+ (x - (7 * Scale()) - AppWindow.Position.X) < (Bounds.Width * Scale()) + 2 &&
+ y < AppWindow.Position.Y + (46 * Scale()) + (additionalHeight * Scale()) &&
+ y >= AppWindow.Position.Y + (1 * Scale()))
{
currentCaption = SelectedCaptionButton.Close;
VisualStateManager.GoToState(Minimize, "Normal", true);
@@ -520,10 +551,10 @@ async void Event(object sender, WinUIEx.Messaging.WindowMessageEventArgs e)
e.Handled = false;
// Minimize Button
- if ((x - 7 * Scale() - this.AppWindow.Position.X) >= (this.Bounds.Width * Scale() - minButtonLeftPos) &&
- (x - 7 * Scale() - this.AppWindow.Position.X) < (this.Bounds.Width * Scale() - maxButtonLeftPos) &&
- y < this.AppWindow.Position.Y + 46 * Scale() + additionalHeight * Scale() &&
- y >= this.AppWindow.Position.Y + 1 * Scale())
+ if ((x - (7 * Scale()) - AppWindow.Position.X) >= ((Bounds.Width * Scale()) - minButtonLeftPos) &&
+ (x - (7 * Scale()) - AppWindow.Position.X) < ((Bounds.Width * Scale()) - maxButtonLeftPos) &&
+ y < AppWindow.Position.Y + (46 * Scale()) + (additionalHeight * Scale()) &&
+ y >= AppWindow.Position.Y + (1 * Scale()))
{
if (currentCaption == SelectedCaptionButton.Minimize)
{
@@ -535,23 +566,26 @@ async void Event(object sender, WinUIEx.Messaging.WindowMessageEventArgs e)
}
// Maximize Button
- else if ((x - 7 * Scale() - this.AppWindow.Position.X) >= (this.Bounds.Width * Scale() - maxButtonLeftPos) &&
- ((x - 7 * Scale() - this.AppWindow.Position.X) < (this.Bounds.Width * Scale() - closeButtonLeftPos)) &&
- y < this.AppWindow.Position.Y + 46 * Scale() + additionalHeight * Scale() &&
- y >= this.AppWindow.Position.Y + 1 * Scale())
+ else if ((x - (7 * Scale()) - AppWindow.Position.X) >= ((Bounds.Width * Scale()) - maxButtonLeftPos) &&
+ ((x - (7 * Scale()) - AppWindow.Position.X) < ((Bounds.Width * Scale()) - closeButtonLeftPos)) &&
+ y < AppWindow.Position.Y + (46 * Scale()) + (additionalHeight * Scale()) &&
+ y >= AppWindow.Position.Y + (1 * Scale()))
{
- if (currentCaption == SelectedCaptionButton.Maximize) RunMaximization();
+ if (currentCaption == SelectedCaptionButton.Maximize)
+ {
+ RunMaximization();
+ }
}
// Close Button
- else if ((x - 7 * Scale() - this.AppWindow.Position.X) >= (this.Bounds.Width * Scale() - closeButtonLeftPos) &&
- (x - 7 * Scale() - this.AppWindow.Position.X) < (this.Bounds.Width * Scale()) + 2 &&
- y < this.AppWindow.Position.Y + 46 * Scale() + additionalHeight * Scale() &&
- y >= this.AppWindow.Position.Y + 1 * Scale())
+ else if ((x - (7 * Scale()) - AppWindow.Position.X) >= ((Bounds.Width * Scale()) - closeButtonLeftPos) &&
+ (x - (7 * Scale()) - AppWindow.Position.X) < (Bounds.Width * Scale()) + 2 &&
+ y < AppWindow.Position.Y + (46 * Scale()) + (additionalHeight * Scale()) &&
+ y >= AppWindow.Position.Y + (1 * Scale()))
{
if (currentCaption == SelectedCaptionButton.Close)
{
- this.Close();
+ Close();
}
}
@@ -587,7 +621,7 @@ async void Event(object sender, WinUIEx.Messaging.WindowMessageEventArgs e)
#endregion MaximizeButton
- double closeWidth = 46;
+ private double closeWidth = 46;
private async void X_ThemeChanged(ThemeListener sender)
{
@@ -618,10 +652,10 @@ public async void CheckMaximization()
{
//CrimsonMaxRes.Style = CrimsonUIButtons.Resources["Maximize"] as Style;
SettingsHelper.SetSetting("Core.Maximized", false);
- SettingsHelper.SetSetting("Core.WindowX", (double)this.AppWindow.Position.X);
- SettingsHelper.SetSetting("Core.WindowY", (double)this.AppWindow.Position.Y);
- SettingsHelper.SetSetting("Core.WindowWidth", this.Bounds.Width + 16);
- SettingsHelper.SetSetting("Core.WindowHeight", this.Bounds.Height + 8);
+ SettingsHelper.SetSetting("Core.WindowX", (double)AppWindow.Position.X);
+ SettingsHelper.SetSetting("Core.WindowY", (double)AppWindow.Position.Y);
+ SettingsHelper.SetSetting("Core.WindowWidth", Bounds.Width + 16);
+ SettingsHelper.SetSetting("Core.WindowHeight", Bounds.Height + 8);
await Task.Delay(10);
VisualStateManager.GoToState(CrimsonMaxRes, "Normal", true);
MaxResGlyph.Glyph = "";
@@ -1002,9 +1036,9 @@ void Event(object sender, WindowMessageEventArgs e)
#endregion CloseButton
*/
- public async void RunMaximization()
+ public void RunMaximization()
{
- var state = (this.Presenter as OverlappedPresenter).State;
+ var state = (Presenter as OverlappedPresenter).State;
if (state == OverlappedPresenterState.Restored)
{
this.Maximize();
@@ -1029,27 +1063,18 @@ public async void RunMaximization()
}
}
- private void CrimsonMinimize_Click(object sender, RoutedEventArgs e)
- {
- this.Minimize();
- }
+ private void CrimsonMinimize_Click(object sender, RoutedEventArgs e) => this.Minimize();
- private void CrimsonMaxRes_Click(object sender, RoutedEventArgs e)
- {
- RunMaximization();
- }
+ private void CrimsonMaxRes_Click(object sender, RoutedEventArgs e) => RunMaximization();
- private void CrimsonClose_Click(object sender, RoutedEventArgs e)
- {
- this.Close();
- }
+ private void CrimsonClose_Click(object sender, RoutedEventArgs e) => Close();
public void LoadBounds()
{
- var appWindow = this.AppWindow;
+ var appWindow = AppWindow;
var titleBar = appWindow.TitleBar;
- RectInt32 rect = new RectInt32(0, 0, (int)(this.Bounds.Width * Scale()), (int)(46 * Scale()));
+ var rect = new RectInt32(0, 0, (int)(Bounds.Width * Scale()), (int)(46 * Scale()));
RectInt32[] rects =
[
@@ -1061,7 +1086,7 @@ public void LoadBounds()
private void Grid_PointerMoved(object sender, PointerRoutedEventArgs e)
{
- if (e.GetCurrentPoint(this.Content).Properties.IsLeftButtonPressed != true)
+ if (e.GetCurrentPoint(Content).Properties.IsLeftButtonPressed != true)
{
currentCaption = SelectedCaptionButton.None;
}
@@ -1072,7 +1097,7 @@ public double Scale()
try
{
// Get the DisplayInformation object for the current view
- DisplayInformation displayInformation = DisplayInformation.CreateForWindowId(this.AppWindow.Id);
+ var displayInformation = DisplayInformation.CreateForWindowId(AppWindow.Id);
// Get the RawPixelsPerViewPixel which gives the scale factor
var scaleFactor = displayInformation.RawPixelsPerViewPixel;
return scaleFactor;
@@ -1085,7 +1110,7 @@ public double Scale()
private void Grid_PointerReleased(object sender, PointerRoutedEventArgs e)
{
- if (e.GetCurrentPoint(this.Content).Properties.IsLeftButtonPressed != true)
+ if (e.GetCurrentPoint(Content).Properties.IsLeftButtonPressed != true)
{
currentCaption = SelectedCaptionButton.None;
}
@@ -1097,9 +1122,9 @@ private void Grid_PointerExited(object sender, PointerRoutedEventArgs e)
{
if (this != null)
{
- if (this.Content != null)
+ if (Content != null)
{
- if (e.GetCurrentPoint(this.Content).Properties.IsLeftButtonPressed != true)
+ if (e.GetCurrentPoint(Content).Properties.IsLeftButtonPressed != true)
{
currentCaption = SelectedCaptionButton.None;
}
diff --git a/Rebound/Package.appxmanifest b/Rebound/Package.appxmanifest
index 8cc143c..c4dce23 100644
--- a/Rebound/Package.appxmanifest
+++ b/Rebound/Package.appxmanifest
@@ -1,4 +1,4 @@
-
+
Rebound
- Lenovo
+ Ivirius
Assets\StoreLogo.png
diff --git a/Rebound/RegionBlock.xaml.cs b/Rebound/RegionBlock.xaml.cs
index f0b0377..5099d73 100644
--- a/Rebound/RegionBlock.xaml.cs
+++ b/Rebound/RegionBlock.xaml.cs
@@ -4,7 +4,6 @@
using System.Threading.Tasks;
using Microsoft.UI.Xaml;
using Microsoft.UI.Xaml.Media.Imaging;
-using WinRT.Interop;
using WinUIEx;
// To learn more about WinUI, the WinUI project structure,
@@ -41,12 +40,12 @@ public RegionBlock()
// Method to retrieve the current user's wallpaper path
private string GetWallpaperPath()
{
- StringBuilder wallpaperPath = new StringBuilder(MAX_PATH);
- SystemParametersInfo(SPI_GETDESKWALLPAPER, MAX_PATH, wallpaperPath, 0);
+ var wallpaperPath = new StringBuilder(MAX_PATH);
+ _ = SystemParametersInfo(SPI_GETDESKWALLPAPER, MAX_PATH, wallpaperPath, 0);
return wallpaperPath.ToString();
}
- public async void LoadWallpaper()
+ public void LoadWallpaper()
{
try
{
@@ -73,7 +72,7 @@ public async void LoadWallpaper()
[DllImport("user32.dll")]
private static extern IntPtr GetClientRect(IntPtr hWnd, out RECT rect);
- private static readonly IntPtr HWND_TOPMOST = new IntPtr(-1);
+ private static readonly IntPtr HWND_TOPMOST = new(-1);
private const uint SWP_NOSIZE = 0x0001;
private const uint SWP_NOMOVE = 0x0002;
@@ -83,11 +82,11 @@ private void BlockTaskbarInteraction()
var desktopHwnd = GetDesktopWindow();
// Get the desktop rectangle
- GetWindowRect(desktopHwnd, out RECT desktopRect);
+ _ = GetWindowRect(desktopHwnd, out var desktopRect);
var windowRect = new RECT { Left = 0, Top = 0, Right = desktopRect.Right, Bottom = desktopRect.Bottom };
// Set your window size and position
- SetWindowPos(hwnd, HWND_TOPMOST, windowRect.Left, windowRect.Top, windowRect.Right - windowRect.Left, windowRect.Bottom - windowRect.Top, SWP_NOMOVE);
+ _ = SetWindowPos(hwnd, HWND_TOPMOST, windowRect.Left, windowRect.Top, windowRect.Right - windowRect.Left, windowRect.Bottom - windowRect.Top, SWP_NOMOVE);
// To intercept input, you'll need a window that captures input events.
// Consider using low-level hooks or other methods to ensure the taskbar cannot be interacted with.
@@ -108,7 +107,7 @@ public async void Load()
LoadWallpaper();
await Task.Delay(200);
//BlockTaskbarInteraction();
- BlockDialog.XamlRoot = this.Content.XamlRoot;
+ BlockDialog.XamlRoot = Content.XamlRoot;
await BlockDialog.ShowAsync();
Close();
}
diff --git a/Rebound/UninstallationWindow.xaml.cs b/Rebound/UninstallationWindow.xaml.cs
index 6ab0ae3..7f10147 100644
--- a/Rebound/UninstallationWindow.xaml.cs
+++ b/Rebound/UninstallationWindow.xaml.cs
@@ -43,7 +43,7 @@ public async void Load(bool deleteAll)
Timer.Start();
TotalSteps = 11;
- TotalSubsteps =
+ TotalSubsteps =
SUBSTEPS_FOLDER + // Rebound 11 Folder
SUBSTEPS_REPLACE_SHORTCUT + // Control Panel
SUBSTEPS_FOLDER + // Rebound 11 Tools
@@ -65,57 +65,57 @@ public async void Load(bool deleteAll)
ReboundProgress.Maximum = TotalSubsteps;
- await RemoveFolder(@"C:\Rebound11");
+ _ = await RemoveFolder(@"C:\Rebound11");
- await ReplaceShortcut(
+ _ = await ReplaceShortcut(
$@"{AppContext.BaseDirectory}\Shortcuts\Included\Control Panel.lnk",
$@"{Environment.GetFolderPath(Environment.SpecialFolder.StartMenu)}\Programs\System Tools\Control Panel.lnk",
"Control Panel");
- await RemoveFolder($@"{Environment.GetFolderPath(Environment.SpecialFolder.StartMenu)}\Programs\Rebound 11 Tools");
+ _ = await RemoveFolder($@"{Environment.GetFolderPath(Environment.SpecialFolder.StartMenu)}\Programs\Rebound 11 Tools");
- await DeleteShortcut(
+ _ = await DeleteShortcut(
$@"{Environment.GetFolderPath(Environment.SpecialFolder.StartMenu)}\Programs\Administrative Tools\Change User Account Control settings.lnk",
"Change User Account Control settings");
- await UninstallAppPackage(
+ _ = await UninstallAppPackage(
InstallationWindowModel.RUN,
"Rebound Run",
$@"{AppContext.BaseDirectory}\Shortcuts\Included\Run.lnk",
$@"{Environment.GetFolderPath(Environment.SpecialFolder.StartMenu)}\Programs\System Tools\Run.lnk",
"Run");
- await DeleteShortcut(
+ _ = await DeleteShortcut(
$@"{Environment.GetFolderPath(Environment.SpecialFolder.StartMenu)}\Programs\Startup\ReboundRunStartup.lnk",
"Rebound Run Startup");
- await UninstallAppPackage(
+ _ = await UninstallAppPackage(
InstallationWindowModel.DEFRAG,
"Rebound Defragment And Optimize Drives",
$@"{AppContext.BaseDirectory}\Shortcuts\Included\dfrgui.lnk",
$@"{Environment.GetFolderPath(Environment.SpecialFolder.CommonAdminTools)}\dfrgui.lnk",
"Defragment And Optimize Drives");
- await UninstallAppPackage(
+ _ = await UninstallAppPackage(
InstallationWindowModel.WINVER,
"Rebound Winver",
$@"",
$@"{Environment.GetFolderPath(Environment.SpecialFolder.CommonAdminTools)}\winver.lnk",
"winver");
- await ReplaceShortcut(
+ _ = await ReplaceShortcut(
$@"{AppContext.BaseDirectory}\Shortcuts\Included\On-Screen Keyboard.lnk",
$@"{Environment.GetFolderPath(Environment.SpecialFolder.StartMenu)}\Programs\Accessibility\On-Screen Keyboard.lnk",
"On-Screen Keyboard");
- await UninstallAppPackage(
+ _ = await UninstallAppPackage(
InstallationWindowModel.TPM,
"Rebound TPM Management",
$@"",
$@"{Environment.GetFolderPath(Environment.SpecialFolder.CommonAdminTools)}\tpm.msc.lnk",
"tpm.msc");
- await UninstallAppPackage(
+ _ = await UninstallAppPackage(
InstallationWindowModel.DISK_CLEANUP,
"Rebound Disk Cleanup",
$@"{AppContext.BaseDirectory}\Shortcuts\Included\Disk Cleanup.lnk",
@@ -124,11 +124,11 @@ await UninstallAppPackage(
if (deleteAll == true)
{
- await UninstallAppPackageWithoutLink(
+ _ = await UninstallAppPackageWithoutLink(
InstallationWindowModel.FILES_APP,
"Files App",
"Files.exe");
- await ApplyRegFile(
+ _ = await ApplyRegFile(
$@"{AppContext.BaseDirectory}\AppRT\Registry\UnsetFilesAsDefault.reg",
"Unset Files as Default");
@@ -189,7 +189,7 @@ public async Task RemoveFolder(string directoryPath)
process.StartInfo.CreateNoWindow = true;
// Start the process
- process.Start();
+ _ = process.Start();
// Read the output and error
var output = process.StandardOutput.ReadToEnd();
@@ -247,7 +247,7 @@ public async Task UninstallAppPackage(string packageFamilyName, string dis
};
// Start the process
- process.Start();
+ _ = process.Start();
var error = process.StandardError.ReadToEnd();
@@ -333,7 +333,7 @@ public async Task UninstallAppPackageWithoutLink(string packageFamilyName,
};
// Start the process
- process.Start();
+ _ = process.Start();
var error = process.StandardError.ReadToEnd();
@@ -427,7 +427,7 @@ public async Task ApplyRegFile(string regFilePath, string regDisplayName)
// Start the process
try
{
- process.Start();
+ _ = process.Start();
process.WaitForExit(); // Optionally wait for the process to finish
}
catch
@@ -445,10 +445,7 @@ public async Task ApplyRegFile(string regFilePath, string regDisplayName)
return Task.CompletedTask;
}
- private void Timer_Tick(object sender, object e)
- {
- TaskManager.StopTask("explorer.exe");
- }
+ private void Timer_Tick(object sender, object e) => TaskManager.StopTask("explorer.exe");
private readonly DispatcherTimer Timer = new();
diff --git a/Rebound/UserControls/HomePageHeaderImage.xaml.cs b/Rebound/UserControls/HomePageHeaderImage.xaml.cs
index 19f06d8..961ad83 100644
--- a/Rebound/UserControls/HomePageHeaderImage.xaml.cs
+++ b/Rebound/UserControls/HomePageHeaderImage.xaml.cs
@@ -12,7 +12,6 @@
using Microsoft.UI.Xaml.Controls;
using Microsoft.UI.Xaml.Hosting;
using Microsoft.UI.Xaml.Media.Animation;
-using Windows.UI;
// To learn more about WinUI, the WinUI project structure,
// and more about our project templates, see: http://aka.ms/winui-project-info.
@@ -108,15 +107,9 @@ private void OnLoading(FrameworkElement sender, object args)
AnimateImage();
}
}
- private void SetBottomGradientStartPoint()
- {
- _bottomGradientStartPointAnimation?.Properties.InsertScalar(GradientSizeKey, 180);
- }
+ private void SetBottomGradientStartPoint() => _bottomGradientStartPointAnimation?.Properties.InsertScalar(GradientSizeKey, 180);
- private void OnImageOpened(object sender, RoutedEventArgs e)
- {
- AnimateImage();
- }
+ private void OnImageOpened(object sender, RoutedEventArgs e) => AnimateImage();
private void AnimateImage()
{
@@ -153,7 +146,7 @@ public static void CreateColorStopsWithEasingFunction(this CompositionGradientBr
var easingFunc = easingType.ToEasingFunction(easingMode);
if (easingFunc != null)
{
- for (float i = colorStopBegin; i < colorStopEnd; i += gap)
+ for (var i = colorStopBegin; i < colorStopEnd; i += gap)
{
var progress = (i - colorStopBegin) / (colorStopEnd - colorStopBegin);
diff --git a/Rebound/Views/HomePage.xaml.cs b/Rebound/Views/HomePage.xaml.cs
index 77fdd02..6decbcf 100644
--- a/Rebound/Views/HomePage.xaml.cs
+++ b/Rebound/Views/HomePage.xaml.cs
@@ -30,8 +30,8 @@ public HomePage()
// Method to retrieve the current user's wallpaper path
private string GetWallpaperPath()
{
- StringBuilder wallpaperPath = new StringBuilder(MAX_PATH);
- SystemParametersInfo(SPI_GETDESKWALLPAPER, MAX_PATH, wallpaperPath, 0);
+ var wallpaperPath = new StringBuilder(MAX_PATH);
+ _ = SystemParametersInfo(SPI_GETDESKWALLPAPER, MAX_PATH, wallpaperPath, 0);
return wallpaperPath.ToString();
}
@@ -39,11 +39,11 @@ public async void LoadWallpaper()
{
try
{
- if (this.ActualTheme == ElementTheme.Light)
+ if (ActualTheme == ElementTheme.Light)
{
BKGImage.Path = "/Assets/Backgrounds/BackgroundLight.png";
}
- if (this.ActualTheme == ElementTheme.Dark)
+ if (ActualTheme == ElementTheme.Dark)
{
BKGImage.Path = "/Assets/Backgrounds/BackgroundDark.png";
}
diff --git a/Rebound/Views/Rebound11Page.xaml.cs b/Rebound/Views/Rebound11Page.xaml.cs
index aa4f543..9b95c67 100644
--- a/Rebound/Views/Rebound11Page.xaml.cs
+++ b/Rebound/Views/Rebound11Page.xaml.cs
@@ -50,18 +50,18 @@ public Rebound11Page()
Rebound11IsNotInstalledGrid.Visibility = Visibility.Collapsed;
DetailsPanel.Visibility = Visibility.Visible;
}
- CheckForUpdatesAsync();
+ _ = CheckForUpdatesAsync();
}
public async void GetWallpaper()
{
try
{
- if (this.ActualTheme == ElementTheme.Light)
+ if (ActualTheme == ElementTheme.Light)
{
BKGImage.Path = "/Assets/Backgrounds/BackgroundLight.png";
}
- if (this.ActualTheme == ElementTheme.Dark)
+ if (ActualTheme == ElementTheme.Dark)
{
BKGImage.Path = "/Assets/Backgrounds/BackgroundDark.png";
}
@@ -81,35 +81,32 @@ public bool IsAdmin()
return principal.IsInRole(WindowsBuiltInRole.Administrator);
}
- public bool IsReboundInstalled()
- {
- return Directory.Exists("C:\\Rebound11");
- }
+ public bool IsReboundInstalled() => Directory.Exists("C:\\Rebound11");
private void Button_Click(object sender, RoutedEventArgs e)
{
var win = new InstallationWindow((bool)FilesCheck.IsChecked, (bool)RunCheck.IsChecked, (bool)DefragCheck.IsChecked, (bool)WinverCheck.IsChecked, (bool)UACCheck.IsChecked, (bool)OSKCheck.IsChecked, (bool)TPMCheck.IsChecked, (bool)DiskCleanupCheck.IsChecked);
- win.Show();
+ _ = win.Show();
}
private async Task CheckForUpdatesAsync()
{
// URL of the text file containing the latest version number
- string versionUrl = "https://ivirius.vercel.app/reboundhubversion.txt";
+ var versionUrl = "https://ivirius.vercel.app/reboundhubversion.txt";
// Use HttpClient to fetch the content
- using HttpClient client = new HttpClient();
+ using var client = new HttpClient();
try
{
// Fetch the version string from the URL
- string latestVersion = await client.GetStringAsync(versionUrl);
+ var latestVersion = await client.GetStringAsync(versionUrl);
// Trim any excess whitespace/newlines from the fetched string
latestVersion = latestVersion.Trim();
// Get the current app version
- string currentVersion = "v0.0.3 ALPHA";
+ var currentVersion = "v0.0.3 ALPHA";
// Compare versions
if (latestVersion == currentVersion)
@@ -150,7 +147,7 @@ private async Task CheckForUpdatesAsync()
}
}
}
- catch (Exception ex)
+ catch (Exception)
{
// Handle any errors that occur during the request
UpdateBar.IsOpen = true;
@@ -193,17 +190,7 @@ private async void Button_Click_2(object sender, RoutedEventArgs e)
App.MainAppWindow.Close();
}
- private void SettingsCard_Click(object sender, RoutedEventArgs e)
- {
- if (File.Exists("C:\\Rebound11\\rwinver.exe"))
- {
- Process.Start("C:\\Rebound11\\rwinver.exe");
- }
- else
- {
- Process.Start("winver.exe");
- }
- }
+ private void SettingsCard_Click(object sender, RoutedEventArgs e) => _ = File.Exists("C:\\Rebound11\\rwinver.exe") ? Process.Start("C:\\Rebound11\\rwinver.exe") : Process.Start("winver.exe");
private async void Button_Click_3(object sender, RoutedEventArgs e)
{
diff --git a/Rebound/Views/ShellPage.xaml.cs b/Rebound/Views/ShellPage.xaml.cs
index 254dd8e..78ce505 100644
--- a/Rebound/Views/ShellPage.xaml.cs
+++ b/Rebound/Views/ShellPage.xaml.cs
@@ -2,9 +2,7 @@
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
-using ABI.System;
using Microsoft.UI.Xaml.Controls;
-using WinUIEx;
// To learn more about WinUI, the WinUI project structure,
// and more about our project templates, see: http://aka.ms/winui-project-info.
@@ -34,7 +32,7 @@ public async void CheckLaunch()
}
}
- private async void NavigationViewControl_SelectionChanged(NavigationView sender, NavigationViewSelectionChangedEventArgs args)
+ private void NavigationViewControl_SelectionChanged(NavigationView sender, NavigationViewSelectionChangedEventArgs args)
{
if ((string)(args.SelectedItem as NavigationViewItem).Tag == "Home")
{
@@ -46,15 +44,12 @@ private async void NavigationViewControl_SelectionChanged(NavigationView sender,
}
if ((string)(args.SelectedItem as NavigationViewItem).Tag == "Control Panel")
{
- Process.Start(new ProcessStartInfo("control:") { UseShellExecute = true });
+ _ = Process.Start(new ProcessStartInfo("control:") { UseShellExecute = true });
sender.SelectedItem = sender.MenuItems[2];
App.MainAppWindow.Close();
}
//NavigationViewControl.Header = (string)(args.SelectedItem as NavigationViewItem).Tag;
}
- private void NavigationViewControl_BackRequested(NavigationView sender, NavigationViewBackRequestedEventArgs args)
- {
- NavigationFrame.GoBack();
- }
+ private void NavigationViewControl_BackRequested(NavigationView sender, NavigationViewBackRequestedEventArgs args) => NavigationFrame.GoBack();
}
diff --git a/Rebound/WindowModels/InstallationWindowModel.cs b/Rebound/WindowModels/InstallationWindowModel.cs
index 9944256..954f207 100644
--- a/Rebound/WindowModels/InstallationWindowModel.cs
+++ b/Rebound/WindowModels/InstallationWindowModel.cs
@@ -3,8 +3,6 @@
using System.Runtime.InteropServices;
using System.Threading.Tasks;
-#pragma warning disable SYSLIB1054 // Use 'LibraryImportAttribute' instead of 'DllImportAttribute' to generate P/Invoke marshalling code at compile time
-
namespace Rebound.WindowModels;
public static class InstallationWindowModel
@@ -33,10 +31,7 @@ public static class SystemLock
[DllImport("user32.dll")]
private static extern void LockWorkStation();
- public static void Lock()
- {
- LockWorkStation();
- }
+ public static void Lock() => LockWorkStation();
}
public static class TaskManager
@@ -65,7 +60,7 @@ public static void StartTask(string task)
try
{
// Start a new explorer.exe process
- Process.Start(task);
+ _ = Process.Start(task);
}
catch
{
@@ -81,31 +76,29 @@ public async Task IsPackageInstalled(string packageFamilyName)
try
{
// Create the PowerShell command
- string command = $"Get-AppxPackage -Name {packageFamilyName}";
+ var command = $"Get-AppxPackage -Name {packageFamilyName}";
// Create a new process to run PowerShell
- using (var process = new Process())
- {
- process.StartInfo.FileName = "powershell.exe";
- process.StartInfo.Arguments = $"-Command \"{command}\"";
- process.StartInfo.RedirectStandardOutput = true;
- process.StartInfo.RedirectStandardError = true;
- process.StartInfo.UseShellExecute = false;
- process.StartInfo.CreateNoWindow = true;
-
- // Start the process
- process.Start();
-
- // Read the output
- string output = await process.StandardOutput.ReadToEndAsync();
- string error = await process.StandardError.ReadToEndAsync();
-
- // Wait for the process to exit
- await process.WaitForExitAsync();
-
- // Check if output contains the package family name
- return !string.IsNullOrWhiteSpace(output) && output.Contains(packageFamilyName);
- }
+ using var process = new Process();
+ process.StartInfo.FileName = "powershell.exe";
+ process.StartInfo.Arguments = $"-Command \"{command}\"";
+ process.StartInfo.RedirectStandardOutput = true;
+ process.StartInfo.RedirectStandardError = true;
+ process.StartInfo.UseShellExecute = false;
+ process.StartInfo.CreateNoWindow = true;
+
+ // Start the process
+ _ = process.Start();
+
+ // Read the output
+ var output = await process.StandardOutput.ReadToEndAsync();
+ var error = await process.StandardError.ReadToEndAsync();
+
+ // Wait for the process to exit
+ await process.WaitForExitAsync();
+
+ // Check if output contains the package family name
+ return !string.IsNullOrWhiteSpace(output) && output.Contains(packageFamilyName);
}
catch (Exception ex)
{
diff --git a/Run/App.xaml.cs b/Run/App.xaml.cs
index 103f2cf..9599554 100644
--- a/Run/App.xaml.cs
+++ b/Run/App.xaml.cs
@@ -7,228 +7,221 @@
using Microsoft.UI.Xaml;
using Rebound.Helpers;
using Rebound.Run.Helpers;
-using Windows.System;
-using Windows.UI.Input.Preview.Injection;
using WinUIEx;
using File = System.IO.File;
using Task = System.Threading.Tasks.Task;
#nullable enable
-#pragma warning disable CA2211 // Non-constant fields should not be visible
-namespace Rebound.Run
+namespace Rebound.Run;
+
+public partial class App : Application
{
- public partial class App : Application
+ private readonly SingleInstanceDesktopApp _singleInstanceApp;
+
+ public App()
{
- private readonly SingleInstanceDesktopApp _singleInstanceApp;
+ this?.InitializeComponent();
- public App()
- {
- this?.InitializeComponent();
+ _singleInstanceApp = new SingleInstanceDesktopApp("Rebound.Run");
+ _singleInstanceApp.Launched += OnSingleInstanceLaunched;
+ }
- _singleInstanceApp = new SingleInstanceDesktopApp("Rebound.Run");
- _singleInstanceApp.Launched += OnSingleInstanceLaunched;
- }
+ public static WindowEx? BackgroundWindow
+ {
+ get; set;
+ }
- public static WindowEx? BackgroundWindow
- {
- get; set;
- }
+ protected override void OnLaunched(LaunchActivatedEventArgs args) => _singleInstanceApp?.Launch(args.Arguments);
- protected override void OnLaunched(LaunchActivatedEventArgs args)
+ private async void OnSingleInstanceLaunched(object? sender, SingleInstanceLaunchEventArgs e)
+ {
+ if (e.IsFirstLaunch)
{
- _singleInstanceApp?.Launch(args.Arguments);
+ _ = await LaunchWork();
}
-
- private async void OnSingleInstanceLaunched(object? sender, SingleInstanceLaunchEventArgs e)
+ else
{
- if (e.IsFirstLaunch)
+ // Get the current process
+ var currentProcess = Process.GetCurrentProcess();
+
+ // Start a new instance of the application
+ if (currentProcess.MainModule != null)
{
- await LaunchWork();
+ _ = Process.Start(currentProcess.MainModule.FileName);
}
- else
- {
- // Get the current process
- Process currentProcess = Process.GetCurrentProcess();
-
- // Start a new instance of the application
- if (currentProcess.MainModule != null) Process.Start(currentProcess.MainModule.FileName);
- // Terminate the current process
- currentProcess?.Kill();
- return;
- }
+ // Terminate the current process
+ currentProcess?.Kill();
+ return;
}
+ }
- public async Task LaunchWork()
- {
- CreateShortcut();
-
- // Initialize the background window
- InitializeBackgroundWindow();
-
- MainWindow = new MainWindow();
+ public async Task LaunchWork()
+ {
+ CreateShortcut();
- // Delay for task execution
- await Task.Delay(5);
+ // Initialize the background window
+ InitializeBackgroundWindow();
- RunBoxReplace();
+ MainWindow = new MainWindow();
- // If started with the "STARTUP" argument, exit early
- if (IsStartupArgumentPresent() == true)
- {
- return 0;
- }
+ // Delay for task execution
+ await Task.Delay(5);
- // Try to activate the main window
- await ActivateMainWindowAsync();
+ RunBoxReplace();
+ // If started with the "STARTUP" argument, exit early
+ if (IsStartupArgumentPresent() == true)
+ {
return 0;
}
- public async void RunBoxReplace()
- {
- await Task.Delay(50);
- if (LegacyRunBoxExists() == true)
- {
- try
- {
- MainWindow.Activate();
- MainWindow.BringToFront();
- }
- catch
- {
- MainWindow = new MainWindow();
- MainWindow.Activate();
- MainWindow.BringToFront();
- }
- }
-
- RunBoxReplace();
- }
+ // Try to activate the main window
+ await ActivateMainWindowAsync();
- // Importing the user32.dll to use GetWindowThreadProcessId
- [DllImport("user32.dll")]
- private static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId);
+ return 0;
+ }
- public static bool IsExplorerWindow(IntPtr hWnd)
+ public async void RunBoxReplace()
+ {
+ await Task.Delay(50);
+ if (LegacyRunBoxExists() == true)
{
- // Get the process ID of the window handle (hWnd)
- GetWindowThreadProcessId(hWnd, out uint processId);
-
try
{
- // Get the process by ID
- Process process = Process.GetProcessById((int)processId);
-
- // Check if the process name is "explorer"
- return process.ProcessName.Equals("explorer", StringComparison.OrdinalIgnoreCase);
+ MainWindow.Activate();
+ _ = MainWindow.BringToFront();
}
- catch (Exception)
+ catch
{
- // If there is an issue retrieving the process, assume it's not Explorer
- return false;
+ MainWindow = new MainWindow();
+ MainWindow.Activate();
+ _ = MainWindow.BringToFront();
}
}
- public static bool LegacyRunBoxExists()
+ RunBoxReplace();
+ }
+
+ // Importing the user32.dll to use GetWindowThreadProcessId
+ [DllImport("user32.dll")]
+ private static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId);
+
+ public static bool IsExplorerWindow(IntPtr hWnd)
+ {
+ // Get the process ID of the window handle (hWnd)
+ _ = GetWindowThreadProcessId(hWnd, out var processId);
+
+ try
{
- // Find the window with the title "Run"
- IntPtr hWnd = Win32Helper.FindWindow(null, "Run");
- //IntPtr hWndtaskmgr2 = Win32Helper.FindWindow("#32770", "Create new task");
+ // Get the process by ID
+ var process = Process.GetProcessById((int)processId);
- if (hWnd != IntPtr.Zero && IsExplorerWindow(hWnd) == true)
- {
- // Send WM_CLOSE to close the window
- bool sent = Win32Helper.PostMessage(hWnd, Win32Helper.WM_CLOSE, IntPtr.Zero, IntPtr.Zero);
-
- Debug.Write(IsExplorerWindow(hWnd));
- if (sent == true)
- {
- return true;
- }
- }
+ // Check if the process name is "explorer"
+ return process.ProcessName.Equals("explorer", StringComparison.OrdinalIgnoreCase);
+ }
+ catch (Exception)
+ {
+ // If there is an issue retrieving the process, assume it's not Explorer
return false;
}
+ }
+
+ public static bool LegacyRunBoxExists()
+ {
+ // Find the window with the title "Run"
+ var hWnd = Win32Helper.FindWindow(null, "Run");
+ //IntPtr hWndtaskmgr2 = Win32Helper.FindWindow("#32770", "Create new task");
- private static void InitializeBackgroundWindow()
+ if (hWnd != IntPtr.Zero && IsExplorerWindow(hWnd) == true)
{
- try
- {
- BackgroundWindow = new()
- {
- SystemBackdrop = new TransparentTintBackdrop(),
- IsMaximizable = false
- };
- BackgroundWindow?.SetExtendedWindowStyle(ExtendedWindowStyle.ToolWindow);
- BackgroundWindow?.SetWindowStyle(WindowStyle.Visible);
- BackgroundWindow?.Activate();
- BackgroundWindow?.MoveAndResize(0, 0, 0, 0);
- BackgroundWindow?.Minimize();
- BackgroundWindow?.SetWindowOpacity(0);
- }
- catch
- {
+ // Send WM_CLOSE to close the window
+ var sent = Win32Helper.PostMessage(hWnd, Win32Helper.WM_CLOSE, IntPtr.Zero, IntPtr.Zero);
+ Debug.Write(IsExplorerWindow(hWnd));
+ if (sent == true)
+ {
+ return true;
}
}
+ return false;
+ }
- private static bool IsStartupArgumentPresent()
+ private static void InitializeBackgroundWindow()
+ {
+ try
{
- return string.Join(" ", Environment.GetCommandLineArgs().Skip(1)).Contains("STARTUP");
+ BackgroundWindow = new()
+ {
+ SystemBackdrop = new TransparentTintBackdrop(),
+ IsMaximizable = false
+ };
+ BackgroundWindow?.SetExtendedWindowStyle(ExtendedWindowStyle.ToolWindow);
+ BackgroundWindow?.SetWindowStyle(WindowStyle.Visible);
+ BackgroundWindow?.Activate();
+ BackgroundWindow?.MoveAndResize(0, 0, 0, 0);
+ BackgroundWindow?.Minimize();
+ BackgroundWindow?.SetWindowOpacity(0);
}
-
- private static async Task ActivateMainWindowAsync()
+ catch
{
- try
- {
- MainWindow?.Activate();
- }
- catch
- {
- // Handle activation error
- }
- await Task.Delay(100); // Ensure main window focus
-
- try
- {
- MainWindow?.Activate(); // Reactivate to ensure focus
- }
- catch
- {
- // Handle activation error
- }
+ }
+ }
- MainWindow?.Show(); // Ensure window is visible
+ private static bool IsStartupArgumentPresent() => string.Join(" ", Environment.GetCommandLineArgs().Skip(1)).Contains("STARTUP");
- // Bring to front explicitly
- ((WindowEx?)MainWindow)?.BringToFront();
+ private static async Task ActivateMainWindowAsync()
+ {
+ try
+ {
+ MainWindow?.Activate();
}
+ catch
+ {
+ // Handle activation error
+ }
+
+ await Task.Delay(100); // Ensure main window focus
- private void CreateShortcut()
+ try
{
- string startupFolderPath = Environment.GetFolderPath(Environment.SpecialFolder.Startup);
- string oldShortcutPath = System.IO.Path.Combine(startupFolderPath, "Rebound.Run.lnk");
- try
- {
- File.Delete(oldShortcutPath);
- }
- catch
- {
+ MainWindow?.Activate(); // Reactivate to ensure focus
+ }
+ catch
+ {
+ // Handle activation error
+ }
- }
- string shortcutPath = System.IO.Path.Combine(startupFolderPath, "Rebound.RunStartup.lnk");
- if (!File.Exists(shortcutPath))
- {
- WshShell shell = new();
- IWshShortcut shortcut = (IWshShortcut)shell.CreateShortcut(shortcutPath);
- shortcut.Description = "Rebound Run";
- shortcut.TargetPath = "C:\\Rebound11\\rrunSTARTUP.exe";
- shortcut?.Save();
- }
+ _ = (MainWindow?.Show()); // Ensure window is visible
+
+ // Bring to front explicitly
+ _ = (MainWindow?.BringToFront());
+ }
+
+ private void CreateShortcut()
+ {
+ var startupFolderPath = Environment.GetFolderPath(Environment.SpecialFolder.Startup);
+ var oldShortcutPath = System.IO.Path.Combine(startupFolderPath, "Rebound.Run.lnk");
+ try
+ {
+ File.Delete(oldShortcutPath);
}
+ catch
+ {
- public static WindowEx? MainWindow;
+ }
+ var shortcutPath = System.IO.Path.Combine(startupFolderPath, "Rebound.RunStartup.lnk");
+ if (!File.Exists(shortcutPath))
+ {
+ WshShell shell = new();
+ var shortcut = (IWshShortcut)shell.CreateShortcut(shortcutPath);
+ shortcut.Description = "Rebound Run";
+ shortcut.TargetPath = "C:\\Rebound11\\rrunSTARTUP.exe";
+ shortcut?.Save();
+ }
}
+
+ public static WindowEx? MainWindow;
}
diff --git a/Run/Helpers/GroupPolicyHelper.cs b/Run/Helpers/GroupPolicyHelper.cs
index c2d8927..591e8e9 100644
--- a/Run/Helpers/GroupPolicyHelper.cs
+++ b/Run/Helpers/GroupPolicyHelper.cs
@@ -1,51 +1,48 @@
using System;
using Microsoft.Win32;
-namespace Rebound.Run.Helpers
+namespace Rebound.Run.Helpers;
+
+public static class GroupPolicyHelper
{
- public static class GroupPolicyHelper
- {
- public const string EXPLORER_GROUP_POLICY_PATH = @"Software\Microsoft\Windows\CurrentVersion\Policies\Explorer";
+ public const string EXPLORER_GROUP_POLICY_PATH = @"Software\Microsoft\Windows\CurrentVersion\Policies\Explorer";
- public static bool? IsGroupPolicyEnabled(string path, string value, int trueValue)
+ public static bool? IsGroupPolicyEnabled(string path, string value, int trueValue)
+ {
+ try
{
- try
+ // Path to the registry key
+ var registryKeyPath = path;
+ // Name of the value we are looking for
+ var valueName = value;
+
+ // Open the registry key
+ using var key = Registry.CurrentUser.OpenSubKey(registryKeyPath);
+ if (key != null)
{
- // Path to the registry key
- string registryKeyPath = path;
- // Name of the value we are looking for
- string valueName = value;
+ var val = key.GetValue(valueName);
- // Open the registry key
- using (RegistryKey key = Registry.CurrentUser.OpenSubKey(registryKeyPath))
+ if (val != null && (int)val == trueValue)
{
- if (key != null)
- {
- object val = key.GetValue(valueName);
-
- if (val != null && (int)val == trueValue)
- {
- // Run box is disabled
- return true;
- }
- else
- {
- // Run box is enabled
- return false;
- }
- }
- else
- {
- // Key not found, assume Run box is enabled
- return null;
- }
+ // Run box is disabled
+ return true;
+ }
+ else
+ {
+ // Run box is enabled
+ return false;
}
}
- catch (Exception)
+ else
{
- // Handle any exceptions
+ // Key not found, assume Run box is enabled
return null;
}
}
+ catch (Exception)
+ {
+ // Handle any exceptions
+ return null;
+ }
}
}
diff --git a/Run/Helpers/Win32Helper.cs b/Run/Helpers/Win32Helper.cs
index 5fffa71..7f78521 100644
--- a/Run/Helpers/Win32Helper.cs
+++ b/Run/Helpers/Win32Helper.cs
@@ -1,50 +1,46 @@
using System;
using System.Runtime.InteropServices;
-#pragma warning disable CA2211 // Non-constant fields should not be visible
-#pragma warning disable CA1401 // P/Invokes should not be visible
-#pragma warning disable SYSLIB1054 // Use 'LibraryImportAttribute' instead of 'DllImportAttribute' to generate P/Invoke marshalling code at compile time
#nullable enable
-namespace Rebound.Run.Helpers
+namespace Rebound.Run.Helpers;
+
+public static partial class Win32Helper
{
- public static partial class Win32Helper
- {
- public const uint WM_CLOSE = 0x0010;
- public const int WH_KEYBOARD_LL = 13;
- public const int WM_KEYDOWN = 0x0100;
- public const int WM_KEYUP = 0x0101;
- public const int VK_R = 0x52;
- public const int VK_LWIN = 0x5B;
- public const int VK_RWIN = 0x5C;
- public const int INPUT_KEYBOARD = 1;
- public const int KEYEVENTF_KEYUP = 0x0002;
-
- public static IntPtr hookId = IntPtr.Zero;
- public static LowLevelKeyboardProc? keyboardProc;
- public delegate IntPtr LowLevelKeyboardProc(int nCode, IntPtr wParam, IntPtr lParam);
-
- [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
- public static extern IntPtr FindWindowEx(IntPtr hwndParent, IntPtr hwndChildAfter, string lpszClass, string lpszWindow);
-
- [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
- public static extern IntPtr FindWindow(string? lpClassName, string? lpWindowName);
-
- [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
- [return: MarshalAs(UnmanagedType.Bool)]
- public static extern bool PostMessage(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam);
-
- [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
- public static extern IntPtr SetWindowsHookEx(int idHook, LowLevelKeyboardProc lpfn, IntPtr hMod, uint dwThreadId);
-
- [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
- [return: MarshalAs(UnmanagedType.Bool)]
- public static extern bool UnhookWindowsHookEx(IntPtr hhk);
-
- [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
- public static extern IntPtr CallNextHookEx(IntPtr hhk, int nCode, IntPtr wParam, IntPtr lParam);
-
- [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
- public static extern IntPtr GetModuleHandle(string lpModuleName);
- }
+ public const uint WM_CLOSE = 0x0010;
+ public const int WH_KEYBOARD_LL = 13;
+ public const int WM_KEYDOWN = 0x0100;
+ public const int WM_KEYUP = 0x0101;
+ public const int VK_R = 0x52;
+ public const int VK_LWIN = 0x5B;
+ public const int VK_RWIN = 0x5C;
+ public const int INPUT_KEYBOARD = 1;
+ public const int KEYEVENTF_KEYUP = 0x0002;
+
+ public static IntPtr hookId = IntPtr.Zero;
+ public static LowLevelKeyboardProc? keyboardProc;
+ public delegate IntPtr LowLevelKeyboardProc(int nCode, IntPtr wParam, IntPtr lParam);
+
+ [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
+ public static extern IntPtr FindWindowEx(IntPtr hwndParent, IntPtr hwndChildAfter, string lpszClass, string lpszWindow);
+
+ [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
+ public static extern IntPtr FindWindow(string? lpClassName, string? lpWindowName);
+
+ [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
+ [return: MarshalAs(UnmanagedType.Bool)]
+ public static extern bool PostMessage(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam);
+
+ [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
+ public static extern IntPtr SetWindowsHookEx(int idHook, LowLevelKeyboardProc lpfn, IntPtr hMod, uint dwThreadId);
+
+ [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
+ [return: MarshalAs(UnmanagedType.Bool)]
+ public static extern bool UnhookWindowsHookEx(IntPtr hhk);
+
+ [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
+ public static extern IntPtr CallNextHookEx(IntPtr hhk, int nCode, IntPtr wParam, IntPtr lParam);
+
+ [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
+ public static extern IntPtr GetModuleHandle(string lpModuleName);
}
diff --git a/Run/Languages/StringTable.cs b/Run/Languages/StringTable.cs
index 80359ae..4a4a55f 100644
--- a/Run/Languages/StringTable.cs
+++ b/Run/Languages/StringTable.cs
@@ -1,29 +1,44 @@
using System.Globalization;
-namespace Rebound.Run.Languages
+namespace Rebound.Run.Languages;
+
+public class StringTable
{
- public class StringTable
- {
- public static string AppTitle;
- public static string Run;
- public static string RunAsAdmin;
- public static string Description;
- public static string Open;
- public static string Arguments;
- public static string Cancel;
- public static string Browse;
+ public static string AppTitle;
+ public static string Run;
+ public static string RunAsAdmin;
+ public static string Description;
+ public static string Open;
+ public static string Arguments;
+ public static string Cancel;
+ public static string Browse;
+ public static string Hover;
+ public static string RunAsAdminLegacy;
+ public static string RunLegacy;
+ public static string RunAsAdminLegacyTooltip;
+ public static string RunAsAdminTooltip;
+ public static string RunLegacyTooltip;
+ public static string RunTooltip;
+ public static string SelectFileToRun;
+ public static string ErrorMessage;
+ public static string Error;
+ public static string Warning;
+ public static string WarningMessage;
+ public static string ErrorMessage2;
+ public static string Win3UIBoxAlreadyOpened;
- public StringTable()
- {
- ReadLanguage();
- }
+ public StringTable()
+ {
+ ReadLanguage();
+ }
- public static void ReadLanguage()
+ public static void ReadLanguage()
+ {
+ // Get the current culture (language) of the system
+ var currentCulture = CultureInfo.CurrentUICulture;
+ switch (currentCulture.Name.ToLower())
{
- // Get the current culture (language) of the system
- CultureInfo currentCulture = CultureInfo.CurrentUICulture;
- if (currentCulture.Name.ToLower() == "en-us")
- {
+ case "en-us":
AppTitle = "Rebound Run";
Run = "Run";
RunAsAdmin = "Run as Administrator";
@@ -32,14 +47,26 @@ public static void ReadLanguage()
Arguments = "Arguments";
Cancel = "Cancel";
Browse = "Browse";
- }
- if (currentCulture.Name.ToLower() == "ro-ro")
- {
+ Hover = "Hover for information";
+ RunAsAdminLegacy = "Run as Administrator (legacy)";
+ RunLegacy = "Run legacy";
+ RunAsAdminLegacyTooltip = "Rebound 11 replaces run entries of classic Windows applets with Rebound apps. To launch the legacy applets as administrator, use this option instead. (Also launches Task Manager without WinUI 3.)";
+ RunAsAdminTooltip = "Run the selected process as administrator. This option will attempt to launch the corresponding Rebound 11 counterpart of the chosen task.";
+ RunLegacyTooltip = "Rebound 11 replaces run entries of classic Windows applets with Rebound apps. To launch the legacy applets, use this option instead. (Also launches Task Manager without WinUI 3.)";
+ RunTooltip = "This option will attempt to launch the corresponding Rebound 11 counterpart of the chosen task.";
+ SelectFileToRun = "Select file to run";
+ ErrorMessage = "The system cannot find the file specified or the command line arguments are invalid.";
+ Error = "Error";
+ Warning = "Important";
+ WarningMessage = "You will have to open this app again to bring back the Windows + R invoke command for Rebound Run.";
+ ErrorMessage2 = "The system cannot find the file specified.";
+ Win3UIBoxAlreadyOpened = "The WinUI 3 run box is already opened.";
+ break;
+ case "ro-ro":
AppTitle = "Executare Rebound";
Run = "Execută";
- }
- if (currentCulture.Name.ToLower() == "de-de")
- {
+ break;
+ case "de-de":
AppTitle = "Rebound Ausführen";
Run = "Ausführen";
RunAsAdmin = "Als Administrator ausführen";
@@ -48,7 +75,55 @@ public static void ReadLanguage()
Arguments = "Argumente";
Cancel = "Abbrechen";
Browse = "Druchsuchen";
- }
+ break;
+ case "ru-ru":
+ AppTitle = "Rebound Выполнить";
+ Run = "Запустить";
+ RunAsAdmin = "Запуск от Администрартора";
+ Description = "Ведите имя программы, папки, документа или ресурса Интернета, которые требуется открыть.";
+ Open = "Открыть";
+ Arguments = "Аргументы";
+ Cancel = "Отмена";
+ Browse = "Обзор...";
+ Hover = "Наведите курсор на элемент для информации";
+ RunAsAdminLegacy = "Запуск от Администрартора (устаревший)";
+ RunLegacy = "Запустить устаревшую версию";
+ RunAsAdminLegacyTooltip = "Rebound 11 заменяет классические приложения Windows на Rebound. Чтобы запустить устаревшие приложения от имени администратора, используйте эту опцию. (Также запускает диспетчер задач из Windows 10).";
+ RunAsAdminTooltip = "Запускает приложение от имени Администратора. При использовании этой опции будут использоваться приложения от Rebound.";
+ RunLegacyTooltip = "Rebound 11 заменяет классические приложения Windows на Rebound. Чтобы запустить устаревшие приложения, используйте эту опцию. (Также запускает диспетчер задач из Windows 10).";
+ RunTooltip = "При использовании этой опции будут использоваться приложения от Rebound.";
+ SelectFileToRun = "Выберите файл для запуска";
+ ErrorMessage = "Не удаётся найти указанный файл. Проверьте, правильно ли указано имя и повторите попытку.";
+ Error = "Ошибка";
+ Warning = "Внимание";
+ WarningMessage = "Вам нужно будет снова открыть это приложение, чтобы вернуть команду Windows + R Выполнить для Rebound Выполнить.";
+ ErrorMessage2 = "Не удаётся найти указанный файл.";
+ Win3UIBoxAlreadyOpened = "Окно выполнить WinUI 3 уже открыто.";
+ break;
+ default:
+ AppTitle = "Rebound Run";
+ Run = "Run";
+ RunAsAdmin = "Run as Administrator";
+ Description = "Type the name of a program, folder, document, or Internet resource, and Windows will open it for you.";
+ Open = "Open";
+ Arguments = "Arguments";
+ Cancel = "Cancel";
+ Browse = "Browse";
+ Hover = "Hover for information";
+ RunAsAdminLegacy = "Run as Administrator (legacy)";
+ RunLegacy = "Run legacy";
+ RunAsAdminLegacyTooltip = "Rebound 11 replaces run entries of classic Windows applets with Rebound apps. To launch the legacy applets as administrator, use this option instead. (Also launches Task Manager without WinUI 3.)";
+ RunAsAdminTooltip = "Run the selected process as administrator. This option will attempt to launch the corresponding Rebound 11 counterpart of the chosen task.";
+ RunLegacyTooltip = "Rebound 11 replaces run entries of classic Windows applets with Rebound apps. To launch the legacy applets, use this option instead. (Also launches Task Manager without WinUI 3.)";
+ RunTooltip = "This option will attempt to launch the corresponding Rebound 11 counterpart of the chosen task.";
+ SelectFileToRun = "Select file to run";
+ ErrorMessage = "The system cannot find the file specified or the command line arguments are invalid.";
+ Error = "Error";
+ Warning = "Important";
+ WarningMessage = "You will have to open this app again to bring back the Windows + R invoke command for Rebound Run.";
+ ErrorMessage2 = "The system cannot find the file specified.";
+ Win3UIBoxAlreadyOpened = "The WinUI 3 run box is already opened.";
+ break;
}
}
}
diff --git a/Run/MainWindow.xaml b/Run/MainWindow.xaml
index 800619d..2c5f566 100644
--- a/Run/MainWindow.xaml
+++ b/Run/MainWindow.xaml
@@ -8,6 +8,7 @@
xmlns:local="using:Rebound.Run"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:winuiex="using:WinUIEx"
+ xmlns:languages="using:Rebound.Run.Languages"
Activated="WindowEx_Activated"
mc:Ignorable="d">
@@ -371,7 +372,7 @@
+ Text="{x:Bind StringTable:StringTable.Open}" />
+ Text="{x:Bind StringTable:StringTable.Arguments}" />
-
+
@@ -433,8 +434,8 @@
+ Text="{x:Bind StringTable:StringTable.RunAsAdmin}"
+ ToolTipService.ToolTip="{x:Bind StringTable:StringTable.RunAsAdminTooltip}">
@@ -447,8 +448,8 @@
+ Text="{x:Bind StringTable:StringTable.RunAsAdminLegacy}"
+ ToolTipService.ToolTip="{x:Bind StringTable:StringTable.RunAsAdminLegacyTooltip}">
@@ -458,8 +459,8 @@
+ Text="{x:Bind StringTable:StringTable.Run}"
+ ToolTipService.ToolTip="{x:Bind StringTable:StringTable.RunTooltip}">
@@ -469,8 +470,8 @@
+ Text="{x:Bind StringTable:StringTable.RunLegacy}"
+ ToolTipService.ToolTip="{x:Bind StringTable:StringTable.RunLegacyTooltip}">
@@ -487,7 +488,7 @@
HorizontalAlignment="Stretch"
VerticalAlignment="Bottom"
Click="Button_Click"
- Content="Cancel">
+ Content="{x:Bind StringTable:StringTable.Cancel}">
@@ -498,7 +499,7 @@
HorizontalAlignment="Stretch"
VerticalAlignment="Bottom"
Click="Button_Click_1"
- Content="Browse" />
+ Content="{x:Bind StringTable:StringTable.Browse}" />
diff --git a/Run/MainWindow.xaml.cs b/Run/MainWindow.xaml.cs
index 5b6f68e..eb01b16 100644
--- a/Run/MainWindow.xaml.cs
+++ b/Run/MainWindow.xaml.cs
@@ -12,8 +12,6 @@
using Microsoft.Win32;
using Rebound.Run.Helpers;
using Rebound.Run.Languages;
-using Windows.Storage.Pickers;
-using Windows.System;
using WinUIEx;
#pragma warning disable IDE0044 // Add readonly modifier
@@ -39,7 +37,7 @@ public MainWindow()
{
this?.InitializeComponent();
StringTable.ReadLanguage();
- this.MoveAndResize(25 * Scale(), (WindowsDisplayAPI.Display.GetDisplays().ToList()[0].CurrentSetting.Resolution.Height - 370 / Scale()) / Scale(), 525, 295);
+ this.MoveAndResize(25 * Scale(), (WindowsDisplayAPI.Display.GetDisplays().ToList()[0].CurrentSetting.Resolution.Height - (370 / Scale())) / Scale(), 525, 295);
IsMinimizable = false;
IsMaximizable = false;
IsResizable = false;
@@ -88,7 +86,7 @@ private void LoadRunHistory(bool clear = false)
}
else
{
- runHistory.Remove(entryValue);
+ _ = runHistory.Remove(entryValue);
runHistory.Clear();
}
}
@@ -269,7 +267,7 @@ public async Task Run(bool runLegacy = false, bool admin = false)
}
catch (Exception)
{
- await ShowMessageDialogAsync($"The system cannot find the file specified.");
+ await ShowMessageDialogAsync(StringTable.ErrorMessage2);
}
}
else
@@ -298,19 +296,19 @@ public async Task Run(bool runLegacy = false, bool admin = false)
try
{
- await ShowMessageDialogAsync($"You will have to open this app again to bring back the Windows + R invoke command for Rebound Run.", "Important");
+ await ShowMessageDialogAsync(StringTable.WarningMessage, StringTable.Warning);
var res = Process.Start(startInfo);
Close();
Process.GetCurrentProcess().Kill();
}
catch (Exception)
{
- await ShowMessageDialogAsync($"The system cannot find the file specified.");
+ await ShowMessageDialogAsync(StringTable.ErrorMessage2);
}
}
else
{
- await ShowMessageDialogAsync($"The WinUI 3 run box is already opened.", "Error");
+ await ShowMessageDialogAsync(StringTable.Win3UIBoxAlreadyOpened, StringTable.Error);
return;
}
Close();
@@ -339,14 +337,9 @@ public async Task RunPowershell(string fileLocation, string arguments, bool admi
var runBoxText = fileLocation;
var argsBoxText = arguments;
- if (!string.IsNullOrWhiteSpace(argsBoxText))
- {
- startInfo.Arguments = $"Start-Process -FilePath '{runBoxText}' -ArgumentList '{argsBoxText}'";
- }
- else
- {
- startInfo.Arguments = $"Start-Process -FilePath '{runBoxText}' ";
- }
+ startInfo.Arguments = !string.IsNullOrWhiteSpace(argsBoxText)
+ ? $"Start-Process -FilePath '{runBoxText}' -ArgumentList '{argsBoxText}'"
+ : $"Start-Process -FilePath '{runBoxText}' ";
// Handle running as administrator
if (admin)
@@ -433,25 +426,13 @@ private async void SplitButton_Click(SplitButton sender, SplitButtonClickEventAr
}
}
- private async void MenuFlyoutItem_Click(object sender, RoutedEventArgs e)
- {
- await Run(true);
- }
+ private async void MenuFlyoutItem_Click(object sender, RoutedEventArgs e) => await Run(true);
- private async void MenuFlyoutItem_Click_1(object sender, RoutedEventArgs e)
- {
- await Run();
- }
+ private async void MenuFlyoutItem_Click_1(object sender, RoutedEventArgs e) => await Run();
- private async void MenuFlyoutItem_Click_2(object sender, RoutedEventArgs e)
- {
- await Run(false, true);
- }
+ private async void MenuFlyoutItem_Click_2(object sender, RoutedEventArgs e) => await Run(false, true);
- private async void MenuFlyoutItem_Click_3(object sender, RoutedEventArgs e)
- {
- await Run(true, true);
- }
+ private async void MenuFlyoutItem_Click_3(object sender, RoutedEventArgs e) => await Run(true, true);
private HashSet PressedKeys = [];
@@ -515,10 +496,7 @@ public void CheckRunBoxText()
VisualStateManager.GoToState(RunButton, "Disabled", true);
}
- private void Button_Click(object sender, RoutedEventArgs e)
- {
- Close();
- }
+ private void Button_Click(object sender, RoutedEventArgs e) => Close();
private async void Button_Click_1(object sender, RoutedEventArgs e)
{
@@ -537,7 +515,7 @@ private async void Button_Click_1(object sender, RoutedEventArgs e)
// Set options for your file picker
openPicker.ViewMode = PickerViewMode.Thumbnail;
openPicker.SuggestedStartLocation = PickerLocationId.Desktop;
- openPicker.CommitButtonText = "Select file to run";
+ openPicker.CommitButtonText = StringTable.SelectFileToRun;
openPicker.FileTypeFilter.Add(".exe");
openPicker.FileTypeFilter.Add(".pif");
openPicker.FileTypeFilter.Add(".com");
@@ -575,13 +553,7 @@ private async void WindowEx_Activated(object sender, WindowActivatedEventArgs ar
}
}
- private void RunBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
- {
- CheckRunBoxText();
- }
+ private void RunBox_SelectionChanged(object sender, SelectionChangedEventArgs e) => CheckRunBoxText();
- private void RunBox_LostFocus(object sender, RoutedEventArgs e)
- {
- CheckRunBoxText();
- }
+ private void RunBox_LostFocus(object sender, RoutedEventArgs e) => CheckRunBoxText();
}
diff --git a/Run/Package.appxmanifest b/Run/Package.appxmanifest
index 459479d..befe7a2 100644
--- a/Run/Package.appxmanifest
+++ b/Run/Package.appxmanifest
@@ -16,7 +16,7 @@
Rebound.Run
- Lenovo
+ Ivirius
Assets\StoreLogo.png
diff --git a/SysInfo/App.xaml.cs b/SysInfo/App.xaml.cs
index addaded..8d12f3b 100644
--- a/SysInfo/App.xaml.cs
+++ b/SysInfo/App.xaml.cs
@@ -12,7 +12,7 @@ public IJsonNavigationViewService JsonNavigationViewService
{
get; set;
}
- public new static App Current => (App)Application.Current;
+ public static new App Current => (App)Application.Current;
public string AppVersion { get; set; } = AssemblyInfoHelper.GetAssemblyVersion();
public string AppName { get; set; } = "Rebound.SysInfo";
public App()
@@ -27,9 +27,10 @@ public App()
protected override void OnLaunched(LaunchActivatedEventArgs args)
{
- m_window = new WindowEx();
-
- m_window.SystemBackdrop = new Microsoft.UI.Xaml.Media.MicaBackdrop();
+ m_window = new WindowEx
+ {
+ SystemBackdrop = new Microsoft.UI.Xaml.Media.MicaBackdrop()
+ };
m_window.AppWindow.DefaultTitleBarShouldMatchAppModeTheme = true;
//CurrentWindow.AppWindow.TitleBar.ExtendsContentIntoTitleBar = true;
@@ -40,7 +41,7 @@ protected override void OnLaunched(LaunchActivatedEventArgs args)
m_window.Content = rootFrame = new Frame();
}
- rootFrame.Navigate(typeof(MainPage));
+ _ = rootFrame.Navigate(typeof(MainPage));
m_window.Title = $"{AppName} v{AppVersion}";
m_window.SetIcon("Assets/icon.ico");
diff --git a/SysInfo/Common/DynamicLocalizerHelper.cs b/SysInfo/Common/DynamicLocalizerHelper.cs
index 0e5b7b4..f97558f 100644
--- a/SysInfo/Common/DynamicLocalizerHelper.cs
+++ b/SysInfo/Common/DynamicLocalizerHelper.cs
@@ -1,10 +1,9 @@
-using Windows.Storage;
-
-namespace Rebound.SysInfo.Common;
+namespace Rebound.SysInfo.Common;
public static class DynamicLocalizerHelper
{
private static string StringsFolderPath { get; set; } = string.Empty;
+ [Obsolete]
public static async Task InitializeLocalizer(params string[] languages)
{
// Initialize a "Strings" folder in the "LocalFolder" for the packaged app.
@@ -15,7 +14,7 @@ public static async Task InitializeLocalizer(params string[] languages)
StorageFolder stringsFolder = await localFolder.CreateFolderAsync(
"Strings",
CreationCollisionOption.OpenIfExists);
- string resourceFileName = "Resources.resw";
+ var resourceFileName = "Resources.resw";
foreach (var item in languages)
{
await LocalizerBuilder.CreateStringResourceFileIfNotExists(stringsFolder, item, resourceFileName);
@@ -30,7 +29,7 @@ public static async Task InitializeLocalizer(params string[] languages)
var stringsFolder = await StorageFolder.GetFolderFromPathAsync(StringsFolderPath);
}
- ILocalizer localizer = await new LocalizerBuilder()
+ var localizer = await new LocalizerBuilder()
.AddStringResourcesFolderForLanguageDictionaries(StringsFolderPath)
.SetOptions(options =>
{
diff --git a/SysInfo/Common/LoggerSetup.cs b/SysInfo/Common/LoggerSetup.cs
index ab253d5..5f8461a 100644
--- a/SysInfo/Common/LoggerSetup.cs
+++ b/SysInfo/Common/LoggerSetup.cs
@@ -12,7 +12,7 @@ public static void ConfigureLogger()
{
if (!Directory.Exists(Constants.LogDirectoryPath))
{
- Directory.CreateDirectory(Constants.LogDirectoryPath);
+ _ = Directory.CreateDirectory(Constants.LogDirectoryPath);
}
Logger = new LoggerConfiguration()
diff --git a/SysInfo/Views/HomeLandingPage.xaml.cs b/SysInfo/Views/HomeLandingPage.xaml.cs
index 4c698f1..99af7c7 100644
--- a/SysInfo/Views/HomeLandingPage.xaml.cs
+++ b/SysInfo/Views/HomeLandingPage.xaml.cs
@@ -24,7 +24,7 @@ private void allLandingPage_OnItemClick(object sender, RoutedEventArgs e)
var args = (ItemClickEventArgs)e;
var item = (DataItem)args.ClickedItem;
- App.Current.JsonNavigationViewService.NavigateTo(item.UniqueId + item.Parameter?.ToString(), item);
+ _ = App.Current.JsonNavigationViewService.NavigateTo(item.UniqueId + item.Parameter?.ToString(), item);
}
}
diff --git a/SysInfo/Views/MainPage.xaml.cs b/SysInfo/Views/MainPage.xaml.cs
index bd74eb6..450cf0e 100644
--- a/SysInfo/Views/MainPage.xaml.cs
+++ b/SysInfo/Views/MainPage.xaml.cs
@@ -18,10 +18,7 @@ private void appTitleBar_BackButtonClick(object sender, RoutedEventArgs e)
}
}
- private void appTitleBar_PaneButtonClick(object sender, RoutedEventArgs e)
- {
- NavView.IsPaneOpen = !NavView.IsPaneOpen;
- }
+ private void appTitleBar_PaneButtonClick(object sender, RoutedEventArgs e) => NavView.IsPaneOpen = !NavView.IsPaneOpen;
private void NavFrame_Navigated(object sender, NavigationEventArgs e)
{
diff --git a/SysInfo/Views/Settings/AppUpdateSettingPage.xaml.cs b/SysInfo/Views/Settings/AppUpdateSettingPage.xaml.cs
index ff12031..c416313 100644
--- a/SysInfo/Views/Settings/AppUpdateSettingPage.xaml.cs
+++ b/SysInfo/Views/Settings/AppUpdateSettingPage.xaml.cs
@@ -1,6 +1,4 @@
-using Windows.System;
-
-namespace Rebound.SysInfo.Views;
+namespace Rebound.SysInfo.Views;
public sealed partial class AppUpdateSettingPage : Page
{
public string CurrentVersion
@@ -44,8 +42,8 @@ private async void CheckForUpdateAsync()
{
try
{
- string username = "Ivirius-Main";
- string repo = "Rebound.SysInfo";
+ var username = "Ivirius-Main";
+ var repo = "Rebound.SysInfo";
TxtLastUpdateCheck.Text = DateTime.Now.ToShortDateString();
Settings.LastUpdateCheck = DateTime.Now.ToShortDateString();
var update = await UpdateHelper.CheckUpdateAsync(username, repo, new Version(App.Current.AppVersion));
@@ -76,15 +74,13 @@ private async void CheckForUpdateAsync()
BtnCheckUpdate.IsEnabled = true;
}
- private async void GoToUpdateAsync()
- {
+ private async void GoToUpdateAsync() =>
//Todo: Change Uri
await Launcher.LaunchUriAsync(new Uri("https://github.com/WinUICommunity/WinUICommunity/releases"));
- }
private async void GetReleaseNotesAsync()
{
- ContentDialog dialog = new ContentDialog()
+ var dialog = new ContentDialog()
{
Title = "Release notes",
CloseButtonText = "Close",
@@ -102,7 +98,7 @@ private async void GetReleaseNotesAsync()
XamlRoot = App.m_window.Content.XamlRoot
};
- await dialog.ShowAsyncQueue();
+ _ = await dialog.ShowAsyncQueue();
}
}
diff --git a/SysInfo/Views/Settings/GeneralSettingPage.xaml.cs b/SysInfo/Views/Settings/GeneralSettingPage.xaml.cs
index 78ffce9..97a126e 100644
--- a/SysInfo/Views/Settings/GeneralSettingPage.xaml.cs
+++ b/SysInfo/Views/Settings/GeneralSettingPage.xaml.cs
@@ -19,7 +19,7 @@ protected override void OnNavigatedTo(NavigationEventArgs e)
private async void NavigateToLogPath_Click(object sender, RoutedEventArgs e)
{
- string folderPath = (sender as HyperlinkButton).Content.ToString();
+ var folderPath = (sender as HyperlinkButton).Content.ToString();
if (Directory.Exists(folderPath))
{
Windows.Storage.StorageFolder folder = await Windows.Storage.StorageFolder.GetFolderFromPathAsync(folderPath);
diff --git a/SysInfo/Views/Settings/ThemeSettingPage.xaml.cs b/SysInfo/Views/Settings/ThemeSettingPage.xaml.cs
index 07f8af8..ad62ef9 100644
--- a/SysInfo/Views/Settings/ThemeSettingPage.xaml.cs
+++ b/SysInfo/Views/Settings/ThemeSettingPage.xaml.cs
@@ -1,6 +1,4 @@
-using Windows.System;
-
-namespace Rebound.SysInfo.Views;
+namespace Rebound.SysInfo.Views;
public sealed partial class ThemeSettingPage : Page
{
public string BreadCrumbBarItemText
@@ -26,20 +24,11 @@ private void ThemeSettingPage_Loaded(object sender, RoutedEventArgs e)
App.Current.ThemeService.SetBackdropComboBoxDefaultItem(CmbBackdrop);
}
- private void CmbTheme_SelectionChanged(object sender, SelectionChangedEventArgs e)
- {
- App.Current.ThemeService.OnThemeComboBoxSelectionChanged(sender);
- }
+ private void CmbTheme_SelectionChanged(object sender, SelectionChangedEventArgs e) => App.Current.ThemeService.OnThemeComboBoxSelectionChanged(sender);
- private void CmbBackdrop_SelectionChanged(object sender, SelectionChangedEventArgs e)
- {
- App.Current.ThemeService.OnBackdropComboBoxSelectionChanged(sender);
- }
+ private void CmbBackdrop_SelectionChanged(object sender, SelectionChangedEventArgs e) => App.Current.ThemeService.OnBackdropComboBoxSelectionChanged(sender);
- private async void OpenWindowsColorSettings(object sender, RoutedEventArgs e)
- {
- _ = await Launcher.LaunchUriAsync(new Uri("ms-settings:colors"));
- }
+ private async void OpenWindowsColorSettings(object sender, RoutedEventArgs e) => _ = await Launcher.LaunchUriAsync(new Uri("ms-settings:colors"));
}
diff --git a/SysInfo/Views/SettingsPage.xaml.cs b/SysInfo/Views/SettingsPage.xaml.cs
index 29e38ad..db182d9 100644
--- a/SysInfo/Views/SettingsPage.xaml.cs
+++ b/SysInfo/Views/SettingsPage.xaml.cs
@@ -13,13 +13,15 @@ private void OnSettingCard_Click(object sender, RoutedEventArgs e)
var item = sender as SettingsCard;
if (item.Tag != null)
{
- Type pageType = Application.Current.GetType().Assembly.GetType($"Rebound.SysInfo.Views.{item.Tag}");
+ var pageType = Application.Current.GetType().Assembly.GetType($"Rebound.SysInfo.Views.{item.Tag}");
if (pageType != null)
{
- SlideNavigationTransitionInfo entranceNavigation = new SlideNavigationTransitionInfo();
- entranceNavigation.Effect = SlideNavigationTransitionEffect.FromRight;
- App.Current.JsonNavigationViewService.NavigateTo(pageType, item.Header, false, entranceNavigation);
+ var entranceNavigation = new SlideNavigationTransitionInfo
+ {
+ Effect = SlideNavigationTransitionEffect.FromRight
+ };
+ _ = App.Current.JsonNavigationViewService.NavigateTo(pageType, item.Header, false, entranceNavigation);
}
}
}
diff --git a/SysInfo/Views/SystemInformationPage.xaml.cs b/SysInfo/Views/SystemInformationPage.xaml.cs
index 5dba7a5..5fd6c17 100644
--- a/SysInfo/Views/SystemInformationPage.xaml.cs
+++ b/SysInfo/Views/SystemInformationPage.xaml.cs
@@ -63,9 +63,9 @@ public static string GetCPUSpecs(string param)
{
PerformanceCounter cpuCounter;
cpuCounter = new PerformanceCounter("Processor", "% Processor Time", "_Total");
- var cpu_util = cpuCounter.NextValue() + "%";
+ _ = cpuCounter.NextValue() + "%";
System.Threading.Thread.Sleep(10);
- cpu_util = cpuCounter.NextValue() + "%";
+ var cpu_util = cpuCounter.NextValue() + "%";
return cpu_util;
}
else
@@ -77,13 +77,13 @@ public static string GetCPUSpecs(string param)
public string GetRAMAmount()
{
- ObjectQuery objectQuery = new ObjectQuery("SELECT * FROM Win32_OperatingSystem");
- ManagementObjectSearcher managementObjectSearcher = new ManagementObjectSearcher(objectQuery);
- ManagementObjectCollection managementObjectCollection = managementObjectSearcher.Get();
+ var objectQuery = new ObjectQuery("SELECT * FROM Win32_OperatingSystem");
+ var managementObjectSearcher = new ManagementObjectSearcher(objectQuery);
+ var managementObjectCollection = managementObjectSearcher.Get();
var amount = "";
foreach (ManagementObject managementObject in managementObjectCollection)
{
- var MemorySize = (UInt64)managementObject["TotalVisibleMemorySize"] / 1048576;
+ var MemorySize = (ulong)managementObject["TotalVisibleMemorySize"] / 1048576;
amount = $"{MemorySize}GB RAM";
}
return amount;
@@ -93,9 +93,9 @@ public string GetRAMUtil()
{
PerformanceCounter ramCounter;
ramCounter = new PerformanceCounter("Memory", "% Committed Bytes In Use", null);
- var ram_util = ramCounter.NextValue() + "%";
+ _ = ramCounter.NextValue() + "%";
System.Threading.Thread.Sleep(10);
- ram_util = ramCounter.NextValue() + "%";
+ var ram_util = ramCounter.NextValue() + "%";
return ram_util;
}
@@ -103,14 +103,16 @@ public static string RAMType
{
get
{
- int type = 0;
+ var type = 0;
- ConnectionOptions connection = new ConnectionOptions();
- connection.Impersonation = ImpersonationLevel.Impersonate;
- ManagementScope scope = new ManagementScope("\\\\.\\root\\CIMV2", connection);
+ var connection = new ConnectionOptions
+ {
+ Impersonation = ImpersonationLevel.Impersonate
+ };
+ var scope = new ManagementScope("\\\\.\\root\\CIMV2", connection);
scope.Connect();
- ObjectQuery query = new ObjectQuery("SELECT * FROM Win32_PhysicalMemory");
- ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query);
+ var query = new ObjectQuery("SELECT * FROM Win32_PhysicalMemory");
+ var searcher = new ManagementObjectSearcher(scope, query);
foreach (ManagementObject queryObj in searcher.Get())
{
type = Convert.ToInt32(queryObj["MemoryType"]);
@@ -122,40 +124,37 @@ public static string RAMType
private static string TypeString(int type)
{
- string outValue = string.Empty;
-
- switch (type)
+ var outValue = type switch
{
- case 0x0: outValue = "Unknown"; break;
- case 0x1: outValue = "Other"; break;
- case 0x2: outValue = "DRAM"; break;
- case 0x3: outValue = "Synchronous DRAM"; break;
- case 0x4: outValue = "Cache DRAM"; break;
- case 0x5: outValue = "EDO"; break;
- case 0x6: outValue = "EDRAM"; break;
- case 0x7: outValue = "VRAM"; break;
- case 0x8: outValue = "SRAM"; break;
- case 0x9: outValue = "RAM"; break;
- case 0xa: outValue = "ROM"; break;
- case 0xb: outValue = "Flash"; break;
- case 0xc: outValue = "EEPROM"; break;
- case 0xd: outValue = "FEPROM"; break;
- case 0xe: outValue = "EPROM"; break;
- case 0xf: outValue = "CDRAM"; break;
- case 0x10: outValue = "3DRAM"; break;
- case 0x11: outValue = "SDRAM"; break;
- case 0x12: outValue = "SGRAM"; break;
- case 0x13: outValue = "RDRAM"; break;
- case 0x14: outValue = "DDR"; break;
- case 0x15: outValue = "DDR2"; break;
- case 0x16: outValue = "DDR2 FB-DIMM"; break;
- case 0x17: outValue = "Undefined 23"; break;
- case 0x18: outValue = "DDR3"; break;
- case 0x19: outValue = "FBD2"; break;
- case 0x1a: outValue = "DDR4"; break;
- default: outValue = "Undefined"; break;
- }
-
+ 0x0 => "Unknown",
+ 0x1 => "Other",
+ 0x2 => "DRAM",
+ 0x3 => "Synchronous DRAM",
+ 0x4 => "Cache DRAM",
+ 0x5 => "EDO",
+ 0x6 => "EDRAM",
+ 0x7 => "VRAM",
+ 0x8 => "SRAM",
+ 0x9 => "RAM",
+ 0xa => "ROM",
+ 0xb => "Flash",
+ 0xc => "EEPROM",
+ 0xd => "FEPROM",
+ 0xe => "EPROM",
+ 0xf => "CDRAM",
+ 0x10 => "3DRAM",
+ 0x11 => "SDRAM",
+ 0x12 => "SGRAM",
+ 0x13 => "RDRAM",
+ 0x14 => "DDR",
+ 0x15 => "DDR2",
+ 0x16 => "DDR2 FB-DIMM",
+ 0x17 => "Undefined 23",
+ 0x18 => "DDR3",
+ 0x19 => "FBD2",
+ 0x1a => "DDR4",
+ _ => "Undefined",
+ };
return outValue;
}
@@ -165,9 +164,9 @@ private string GetCurrentWallpaper()
// The current wallpaper path is stored in the registry at HKEY_CURRENT_USER\\Control Panel\\Desktop\\WallPaper
- RegistryKey rkWallPaper = Registry.CurrentUser.OpenSubKey("Control Panel\\Desktop", false);
+ var rkWallPaper = Registry.CurrentUser.OpenSubKey("Control Panel\\Desktop", false);
- string WallpaperPath = rkWallPaper.GetValue("WallPaper").ToString();
+ var WallpaperPath = rkWallPaper.GetValue("WallPaper").ToString();
rkWallPaper.Close();
diff --git a/SysInfo/Views/UserControls/BreadcrumbBarUserControl.xaml.cs b/SysInfo/Views/UserControls/BreadcrumbBarUserControl.xaml.cs
index 4b39085..8271375 100644
--- a/SysInfo/Views/UserControls/BreadcrumbBarUserControl.xaml.cs
+++ b/SysInfo/Views/UserControls/BreadcrumbBarUserControl.xaml.cs
@@ -47,10 +47,10 @@ private void BreadcrumbBarUserControl_Loaded(object sender, RoutedEventArgs e)
private void BreadcrumbBar_ItemClicked(BreadcrumbBar sender, BreadcrumbBarItemClickedEventArgs args)
{
- int numItemsToGoBack = BreadcrumbBarCollection.Count - args.Index - 1;
- for (int i = 0; i < numItemsToGoBack; i++)
+ var numItemsToGoBack = BreadcrumbBarCollection.Count - args.Index - 1;
+ for (var i = 0; i < numItemsToGoBack; i++)
{
- App.Current.JsonNavigationViewService.GoBack();
+ _ = App.Current.JsonNavigationViewService.GoBack();
}
}
}
diff --git a/TrustedPlatform/App.xaml.cs b/TrustedPlatform/App.xaml.cs
index bb0d993..bc6d5cb 100644
--- a/TrustedPlatform/App.xaml.cs
+++ b/TrustedPlatform/App.xaml.cs
@@ -2,7 +2,6 @@
using WinUIEx;
#nullable enable
-#pragma warning disable CA2211 // Non-constant fields should not be visible
namespace Rebound.TrustedPlatform;
@@ -20,10 +19,7 @@ public App()
_singleInstanceApp.Launched += OnSingleInstanceLaunched;
}
- protected override void OnLaunched(LaunchActivatedEventArgs args)
- {
- _singleInstanceApp?.Launch(args.Arguments);
- }
+ protected override void OnLaunched(LaunchActivatedEventArgs args) => _singleInstanceApp?.Launch(args.Arguments);
private void OnSingleInstanceLaunched(object? sender, SingleInstanceLaunchEventArgs e)
{
@@ -48,6 +44,6 @@ private void OnSingleInstanceLaunched(object? sender, SingleInstanceLaunchEventA
private static void LaunchWork()
{
MainAppWindow = new MainWindow();
- MainAppWindow.Show();
+ _ = MainAppWindow.Show();
}
}
\ No newline at end of file
diff --git a/TrustedPlatform/GlobalUsings.cs b/TrustedPlatform/GlobalUsings.cs
index c4a84c9..4e47140 100644
--- a/TrustedPlatform/GlobalUsings.cs
+++ b/TrustedPlatform/GlobalUsings.cs
@@ -1,4 +1,3 @@
-global using Microsoft.UI;
-global using Microsoft.UI.Xaml;
+global using Microsoft.UI.Xaml;
global using Microsoft.UI.Xaml.Controls;
global using Rebound.TrustedPlatform.Views;
diff --git a/TrustedPlatform/MainWindow.xaml.cs b/TrustedPlatform/MainWindow.xaml.cs
index 92790da..88d055c 100644
--- a/TrustedPlatform/MainWindow.xaml.cs
+++ b/TrustedPlatform/MainWindow.xaml.cs
@@ -8,7 +8,10 @@ namespace Rebound.TrustedPlatform;
public sealed partial class MainWindow : WindowEx
{
- public TitleBarService TitleBarService { get; set; }
+ public TitleBarService TitleBarService
+ {
+ get; set;
+ }
public MainWindow()
{
@@ -17,14 +20,14 @@ public MainWindow()
SystemBackdrop = new MicaBackdrop();
AppWindow.DefaultTitleBarShouldMatchAppModeTheme = true;
WindowTitle.Text = Title;
- RootFrame.Navigate(typeof(MainPage));
+ _ = RootFrame.Navigate(typeof(MainPage));
TitleBarService = new(this, AccentStrip, TitleBarIcon, WindowTitle, Close, CrimsonMaxRes, Minimize, MaxResGlyph, ContentGrid);
TitleBarService.SetWindowIcon($"Assets\\icon.ico");
MinHeight = 600;
- MinWidth = 500;
-
+ MinWidth = 500;
+
var rects = Display.GetDPIAwareDisplayRect(this);
if (rects.Height < 900 || rects.Width < 1200)
{
@@ -32,8 +35,5 @@ public MainWindow()
}
}
- private void WindowEx_Closed(object sender, WindowEventArgs args)
- {
- App.MainAppWindow = null;
- }
+ private void WindowEx_Closed(object sender, WindowEventArgs args) => App.MainAppWindow = null;
}
\ No newline at end of file
diff --git a/TrustedPlatform/Models/TpmManager.cs b/TrustedPlatform/Models/TpmManager.cs
index deb1768..0396973 100644
--- a/TrustedPlatform/Models/TpmManager.cs
+++ b/TrustedPlatform/Models/TpmManager.cs
@@ -1,10 +1,8 @@
-using System;
-using System.ComponentModel;
+using System.ComponentModel;
using System.Diagnostics;
using System.Management;
using System.Text;
using Tpm2Lib;
-using Windows.Devices.Spi;
public class TpmManager : INotifyPropertyChanged
{
@@ -96,28 +94,23 @@ public TpmManager()
GetTpmInfo(); // No assignment, just calling the method
}
- public void RefreshTpmInfo()
- {
- GetTpmInfo(); // No assignment, just calling the method
- }
+ public void RefreshTpmInfo() => GetTpmInfo(); // No assignment, just calling the method
private void GetTpmInfo()
{
try
{
- using (ManagementObjectSearcher searcher = new ManagementObjectSearcher(@"root\CIMV2\Security\MicrosoftTpm", "SELECT * FROM Win32_Tpm"))
+ using var searcher = new ManagementObjectSearcher(@"root\CIMV2\Security\MicrosoftTpm", "SELECT * FROM Win32_Tpm");
+ foreach (ManagementObject queryObj in searcher.Get())
{
- foreach (ManagementObject queryObj in searcher.Get())
- {
- ManufacturerName = queryObj["ManufacturerID"] != null ? ConvertManufacturerIdToName((uint)queryObj["ManufacturerID"]) : "Unknown";
- ManufacturerVersion = queryObj["ManufacturerVersion"]?.ToString() ?? "Unknown";
- SpecificationVersion = queryObj["SpecVersion"]?.ToString() ?? "Unknown";
- TpmSubVersion = queryObj["ManufacturerVersion"]?.ToString() ?? "Unknown";
- PcClientSpecVersion = queryObj["SpecVersion"]?.ToString() ?? "Unknown";
- PcrValues = GetPcrValues();
-
- Status = queryObj["IsActivated_InitialValue"] != null && (bool)queryObj["IsActivated_InitialValue"] ? "Ready" : "Not Ready";
- }
+ ManufacturerName = queryObj["ManufacturerID"] != null ? ConvertManufacturerIdToName((uint)queryObj["ManufacturerID"]) : "Unknown";
+ ManufacturerVersion = queryObj["ManufacturerVersion"]?.ToString() ?? "Unknown";
+ SpecificationVersion = queryObj["SpecVersion"]?.ToString() ?? "Unknown";
+ TpmSubVersion = queryObj["ManufacturerVersion"]?.ToString() ?? "Unknown";
+ PcClientSpecVersion = queryObj["SpecVersion"]?.ToString() ?? "Unknown";
+ PcrValues = GetPcrValues();
+
+ Status = queryObj["IsActivated_InitialValue"] != null && (bool)queryObj["IsActivated_InitialValue"] ? "Ready" : "Not Ready";
}
}
catch (Exception ex)
@@ -150,15 +143,15 @@ public string GetPcrValues()
try
{
// Specify PCR selection for reading (e.g., PCR 0, 1, 2)
- PcrSelection[] pcrSelectionIn = { new PcrSelection(TpmAlgId.Sha256, new uint[] { 0, 1, 2 }) };
+ PcrSelection[] pcrSelectionIn = { new(TpmAlgId.Sha256, new uint[] { 0, 1, 2 }) };
PcrSelection[] pcrSelectionOut;
Tpm2bDigest[] pcrValues;
// Read PCR values
- tpm.PcrRead(pcrSelectionIn, out pcrSelectionOut, out pcrValues);
+ _ = tpm.PcrRead(pcrSelectionIn, out pcrSelectionOut, out pcrValues);
// Build a string to display PCR values
- StringBuilder pcrStringBuilder = new StringBuilder();
+ var pcrStringBuilder = new StringBuilder();
// Check if pcrValues has entries
if (pcrValues.Length == 0)
@@ -166,9 +159,9 @@ public string GetPcrValues()
return "No PCR values available.";
}
- for (int i = 0; i < pcrSelectionOut.Length; i++)
+ for (var i = 0; i < pcrSelectionOut.Length; i++)
{
- pcrStringBuilder.AppendLine($"PCR {i}: {BitConverter.ToString(pcrValues[i].buffer)}");
+ _ = pcrStringBuilder.AppendLine($"PCR {i}: {BitConverter.ToString(pcrValues[i].buffer)}");
}
return pcrStringBuilder.ToString();
@@ -193,8 +186,5 @@ public string GetPcrValues()
}
}
- protected virtual void OnPropertyChanged(string propertyName)
- {
- PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
- }
+ protected virtual void OnPropertyChanged(string propertyName) => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
diff --git a/TrustedPlatform/Models/TpmReset.cs b/TrustedPlatform/Models/TpmReset.cs
index 5568a71..31a90e8 100644
--- a/TrustedPlatform/Models/TpmReset.cs
+++ b/TrustedPlatform/Models/TpmReset.cs
@@ -9,7 +9,7 @@ public static async Task ResetTpmAsync(ContentDialog dial)
try
{
// Path to the PowerShell script
- string scriptPath = Path.Combine(Path.GetTempPath(), "Reset-TPM.ps1");
+ var scriptPath = Path.Combine(Path.GetTempPath(), "Reset-TPM.ps1");
// Write the PowerShell script to a temporary file
File.WriteAllText(scriptPath, @"
@@ -19,7 +19,7 @@ public static async Task ResetTpmAsync(ContentDialog dial)
");
// Set up the process to run PowerShell with elevated privileges
- ProcessStartInfo psi = new ProcessStartInfo
+ var psi = new ProcessStartInfo
{
FileName = "powershell.exe",
Arguments = $"-NoProfile -ExecutionPolicy Bypass -File \"{scriptPath}\"",
@@ -47,7 +47,7 @@ public static async Task ResetTpmAsync(ContentDialog dial)
}
dial.IsSecondaryButtonEnabled = true;
}
- catch (Exception ex)
+ catch (Exception)
{
// Handle exceptions and update InfoBar for failure
dial.Content = $"Operation cancelled from User Account Control.";
diff --git a/TrustedPlatform/Models/TpmViewModel.cs b/TrustedPlatform/Models/TpmViewModel.cs
index 267a110..e2e37c7 100644
--- a/TrustedPlatform/Models/TpmViewModel.cs
+++ b/TrustedPlatform/Models/TpmViewModel.cs
@@ -25,7 +25,7 @@ public TpmViewModel()
public async Task LoadTpmInfoAsync()
{
// Call the method to refresh TPM info
- await Task.Run(() => _tpmManager.RefreshTpmInfo());
+ await Task.Run(_tpmManager.RefreshTpmInfo);
// Notify properties
OnPropertyChanged(nameof(ManufacturerName));
OnPropertyChanged(nameof(ManufacturerVersion));
@@ -37,8 +37,5 @@ public async Task LoadTpmInfoAsync()
OnPropertyChanged(nameof(PcrValues));
}
- protected virtual void OnPropertyChanged(string propertyName)
- {
- PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
- }
+ protected virtual void OnPropertyChanged(string propertyName) => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
diff --git a/TrustedPlatform/Views/MainPage.xaml.cs b/TrustedPlatform/Views/MainPage.xaml.cs
index dd50bb4..f736586 100644
--- a/TrustedPlatform/Views/MainPage.xaml.cs
+++ b/TrustedPlatform/Views/MainPage.xaml.cs
@@ -15,7 +15,7 @@ public TpmManager TpmManager
public MainPage()
{
- this.InitializeComponent();
+ InitializeComponent();
// Initialize TpmManager for the original properties
TpmManager = new TpmManager();
@@ -23,7 +23,7 @@ public MainPage()
ViewModelTpm = new TpmViewModel();
// Set DataContext to TpmManager for original properties
- this.DataContext = this;
+ DataContext = this;
// Load new TPM information asynchronously
_ = ViewModelTpm.LoadTpmInfoAsync();
@@ -42,13 +42,13 @@ public MainPage()
StatusBar.Title = $"Status: {ViewModelTpm.Status}";
}
- ContentDialog dial;
+ private ContentDialog dial;
private async void Button_Click(object sender, RoutedEventArgs e)
{
var dialog = new ContentDialog()
{
- XamlRoot = this.XamlRoot,
+ XamlRoot = XamlRoot,
PrimaryButtonText = "Reset",
SecondaryButtonText = "Cancel",
DefaultButton = ContentDialogButton.Primary,
@@ -58,14 +58,13 @@ private async void Button_Click(object sender, RoutedEventArgs e)
dial = dialog;
dialog.PrimaryButtonClick += Dialog_PrimaryButtonClick;
dialog.SecondaryButtonClick += Dialog_SecondaryButtonClick;
- await dialog.ShowAsync(); // Show the dialog
+ _ = await dialog.ShowAsync(); // Show the dialog
}
private void Dialog_SecondaryButtonClick(ContentDialog sender, ContentDialogButtonClickEventArgs args)
{
sender.Hide();
dial = null;
- sender = null;
}
private async void Dialog_PrimaryButtonClick(ContentDialog sender, ContentDialogButtonClickEventArgs args)