Skip to content

Portable Tool for an Ideal Windows Setup

monitoring the load (CPU, RAM) in the background & getting the number of processes via WinAPI

Greedeks6e61285f1299
diff --git a/.Source/GTweak/Utilities/Configuration/MonitoringService.cs b/.Source/GTweak/Utilities/Configuration/MonitoringService.cs
index 6e3fe7c5..eee218c1 100644
--- a/.Source/GTweak/Utilities/Configuration/MonitoringService.cs
+++ b/.Source/GTweak/Utilities/Configuration/MonitoringService.cs
@@ -13,8 +13,8 @@ namespace GTweak.Utilities.Configuration
internal event Action<DeviceType> HandleDevicesEvents;
private readonly List<ManagementEventWatcher> _eventWatchers = new List<ManagementEventWatcher>();
- internal int GetMemoryUsage => GetPhysicalAvailableMemory();
- internal string GetNumberRunningProcesses => Process.GetProcesses().Length.ToString();
+ internal string GetNumberRunningProcesses => GetProcessCount().Result;
+ internal int GetMemoryUsage => GetPhysicalAvailableMemory().Result;
internal static int GetProcessorUsage { get; private set; } = 1;
internal enum DeviceType
@@ -48,21 +48,58 @@ namespace GTweak.Utilities.Configuration
internal MemoryStatus() => dwLength = (uint)Marshal.SizeOf(typeof(MemoryStatus));
}
+ [DllImport("psapi.dll", SetLastError = true)]
+ static extern bool EnumProcesses([Out] uint[] lpidProcess, uint cb, out uint lpcbNeeded);
+
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern bool GlobalMemoryStatusEx([In, Out] MemoryStatus lpBuffer);
[DllImport("kernel32.dll", SetLastError = true)]
private static extern bool GetSystemTimes(out SystemTime lpIdleTime, out SystemTime lpKernelTime, out SystemTime lpUserTime);
- private static int GetPhysicalAvailableMemory()
+
+ private static Task<string> GetProcessCount()
{
- MemoryStatus memStatus = new MemoryStatus();
- if (!GlobalMemoryStatusEx(memStatus))
- return 0;
+ return Task.Run(() =>
+ {
+ uint capacity = 1024;
+
+ for (int attempt = 0; attempt < 3; attempt++)
+ {
+ uint[] buffer = new uint[capacity];
+ bool success = EnumProcesses(buffer, capacity * sizeof(uint), out uint bytesNeeded);
- int totalMemory = (int)(memStatus.ullTotalPhys / 1048576);
- int availableMemory = (int)(memStatus.ullAvailPhys / 1048576);
- return (int)((float)(totalMemory - availableMemory) / totalMemory * 100);
+ if (!success)
+ {
+ if (attempt == 2) break;
+
+ if (bytesNeeded > capacity * sizeof(uint))
+ capacity = bytesNeeded / sizeof(uint) + 1;
+
+ continue;
+ }
+
+ if (bytesNeeded < capacity * sizeof(uint))
+ return (bytesNeeded / sizeof(uint)).ToString();
+
+ capacity = bytesNeeded / sizeof(uint) + 1;
+ }
+
+ return Process.GetProcesses().Length.ToString();
+ });
+ }
+ private static Task<int> GetPhysicalAvailableMemory()
+ {
+ return Task.Run(() =>
+ {
+ MemoryStatus memStatus = new MemoryStatus();
+ if (!GlobalMemoryStatusEx(memStatus))
+ return 0;
+
+ int totalMemory = (int)(memStatus.ullTotalPhys / 1048576);
+ int availableMemory = (int)(memStatus.ullAvailPhys / 1048576);
+ return (int)((float)(totalMemory - availableMemory) / totalMemory * 100);
+ });
}
internal async Task GetTotalProcessorUsage()
@@ -70,26 +107,29 @@ namespace GTweak.Utilities.Configuration
bool success = false;
try
{
- static ulong ConvertTimeToTicks(SystemTime systemTime) => ((ulong)systemTime.dwHighDateTime << 32) | systemTime.dwLowDateTime;
+ await Task.Run(async () =>
+ {
+ static ulong ConvertTimeToTicks(SystemTime systemTime) => ((ulong)systemTime.dwHighDateTime << 32) | systemTime.dwLowDateTime;
- if (!GetSystemTimes(out SystemTime idleTime, out SystemTime kernelTime, out SystemTime userTime))
- return;
+ if (!GetSystemTimes(out SystemTime idleTime, out SystemTime kernelTime, out SystemTime userTime))
+ return;
- ulong idleTicks = ConvertTimeToTicks(idleTime);
- ulong totalTicks = ConvertTimeToTicks(kernelTime) + ConvertTimeToTicks(userTime);
+ ulong idleTicks = ConvertTimeToTicks(idleTime);
+ ulong totalTicks = ConvertTimeToTicks(kernelTime) + ConvertTimeToTicks(userTime);
- await Task.Delay(1000);
+ await Task.Delay(1000);
- if (!GetSystemTimes(out idleTime, out kernelTime, out userTime))
- return;
+ if (!GetSystemTimes(out idleTime, out kernelTime, out userTime))
+ return;
- ulong newIdleTicks = ConvertTimeToTicks(idleTime);
- ulong newTotalTicks = ConvertTimeToTicks(kernelTime) + ConvertTimeToTicks(userTime);
+ ulong newIdleTicks = ConvertTimeToTicks(idleTime);
+ ulong newTotalTicks = ConvertTimeToTicks(kernelTime) + ConvertTimeToTicks(userTime);
- ulong totalTicksDiff = newTotalTicks - totalTicks;
+ ulong totalTicksDiff = newTotalTicks - totalTicks;
- GetProcessorUsage = (int)(100.0 * (totalTicksDiff - (newIdleTicks - idleTicks)) / totalTicksDiff);
- success = true;
+ GetProcessorUsage = Math.Min(100, Math.Max(0, (int)(100.0 * (totalTicksDiff - (newIdleTicks - idleTicks)) / totalTicksDiff)));
+ success = true;
+ }).ConfigureAwait(false);
}
catch (Exception ex) { ErrorLogging.LogDebug(ex); }
finally { if (!success) GetProcessorUsage = 1; }
diff --git a/.Source/GTweak/View/DataSystemView.xaml.cs b/.Source/GTweak/View/DataSystemView.xaml.cs
index 339fc37f..ffc94e2e 100644
--- a/.Source/GTweak/View/DataSystemView.xaml.cs
+++ b/.Source/GTweak/View/DataSystemView.xaml.cs
@@ -36,13 +36,16 @@ namespace GTweak.View
App.LanguageChanged += delegate
{
- if (new Dictionary<SystemDiagnostics.ConnectionStatus, string>
+ Dispatcher.Invoke(() =>
{
- { SystemDiagnostics.ConnectionStatus.Lose, "connection_lose_systemInformation" },
- { SystemDiagnostics.ConnectionStatus.Block, "connection_block_systemInformation" },
- { SystemDiagnostics.ConnectionStatus.Limited, "connection_limited_systemInformation" }
- }.TryGetValue(SystemDiagnostics.CurrentConnection, out string resourceKey)) { SystemDiagnostics.HardwareData.UserIPAddress = (string)FindResource(resourceKey); }
- DataContext = new DataSystemVM();
+ if (new Dictionary<SystemDiagnostics.ConnectionStatus, string>
+ {
+ { SystemDiagnostics.ConnectionStatus.Lose, "connection_lose_systemInformation" },
+ { SystemDiagnostics.ConnectionStatus.Block, "connection_block_systemInformation" },
+ { SystemDiagnostics.ConnectionStatus.Limited, "connection_limited_systemInformation" }
+ }.TryGetValue(SystemDiagnostics.CurrentConnection, out string resourceKey)) { SystemDiagnostics.HardwareData.UserIPAddress = (string)FindResource(resourceKey); }
+ DataContext = new DataSystemVM();
+ });
};
timer = new TimerControlManager(TimeSpan.Zero, TimerControlManager.TimerMode.CountUp, async time =>
@@ -57,16 +60,20 @@ namespace GTweak.View
{
BackgroundQueue backgroundQueue = new BackgroundQueue();
await backgroundQueue.QueueTask(delegate { _systemDiagnostics.GetUserIpAddress(); });
- DataContext = new DataSystemVM();
+ Dispatcher.Invoke(() => DataContext = new DataSystemVM());
}
- if (BtnHiddenIP.IsChecked.Value & BtnHiddenIP.Visibility == Visibility.Hidden & !SystemDiagnostics.isIPAddressFormatValid)
+ Dispatcher.Invoke(() =>
{
- DoubleAnimation doubleAnim = new DoubleAnimation(0, (Duration)TimeSpan.FromSeconds(0.18));
- doubleAnim.Completed += delegate { SettingsEngine.IsHiddenIpAddress = false; };
- Timeline.SetDesiredFrameRate(doubleAnim, 240);
- IpAddress.Effect.BeginAnimation(BlurEffect.RadiusProperty, doubleAnim);
- }
+ if (BtnHiddenIP.IsChecked.Value & BtnHiddenIP.Visibility == Visibility.Hidden & !SystemDiagnostics.isIPAddressFormatValid)
+ {
+ DoubleAnimation doubleAnim = new DoubleAnimation(0, (Duration)TimeSpan.FromSeconds(0.18));
+ doubleAnim.Completed += delegate { SettingsEngine.IsHiddenIpAddress = false; };
+ Timeline.SetDesiredFrameRate(doubleAnim, 240);
+ IpAddress.Effect.BeginAnimation(BlurEffect.RadiusProperty, doubleAnim);
+ }
+ });
+
});
timer.Start();
}
@@ -99,22 +106,19 @@ namespace GTweak.View
}
private void AnimationPopup()
{
- Dispatcher.Invoke(() =>
- {
- PopupCopy.IsOpen = true;
- CopyTextToastBody.BeginAnimation(ContextMenu.OpacityProperty, FadeAnimation.FadeIn(0.9, 0.27, () => { PopupCopy.IsOpen = false; }, true));
+ PopupCopy.IsOpen = true;
+ CopyTextToastBody.BeginAnimation(UIElement.OpacityProperty, FadeAnimation.FadeIn(0.9, 0.27, () => { PopupCopy.IsOpen = false; }, true));
- DoubleAnimation offsetAnim = new DoubleAnimation()
- {
- From = -20,
- To = -50,
- SpeedRatio = 8,
- EasingFunction = new QuadraticEase(),
- Duration = TimeSpan.FromSeconds(3)
- };
- Timeline.SetDesiredFrameRate(offsetAnim, 240);
- PopupCopy.BeginAnimation(Popup.VerticalOffsetProperty, offsetAnim);
- });
+ DoubleAnimation offsetAnim = new DoubleAnimation()
+ {
+ From = -20,
+ To = -50,
+ SpeedRatio = 8,
+ EasingFunction = new QuadraticEase(),
+ Duration = TimeSpan.FromSeconds(3)
+ };
+ Timeline.SetDesiredFrameRate(offsetAnim, 240);
+ PopupCopy.BeginAnimation(Popup.VerticalOffsetProperty, offsetAnim);
}
#endregion
diff --git a/.Source/GTweak/Windows/MainWindow.xaml.cs b/.Source/GTweak/Windows/MainWindow.xaml.cs
index b9e7fbf3..55013a29 100644
--- a/.Source/GTweak/Windows/MainWindow.xaml.cs
+++ b/.Source/GTweak/Windows/MainWindow.xaml.cs
@@ -43,38 +43,35 @@ namespace GTweak
private void AnimationSettingsMenu()
{
- Dispatcher.Invoke(() =>
- {
- Storyboard storyboard = new Storyboard();
+ Storyboard storyboard = new Storyboard();
- DoubleAnimation rotateAnimation = new DoubleAnimation()
- {
- From = 0.0,
- To = 360,
- EasingFunction = new QuadraticEase(),
- SpeedRatio = 2.0,
- Duration = TimeSpan.FromSeconds(1)
- };
-
- DoubleAnimation widthAnimation = new DoubleAnimation()
- {
- From = SettingsMenu.Width != 400 ? 0 : 400,
- To = SettingsMenu.Width != 400 ? 400 : 0,
- EasingFunction = new QuadraticEase(),
- SpeedRatio = 2.0,
- Duration = TimeSpan.FromSeconds(1)
- };
-
- Timeline.SetDesiredFrameRate(rotateAnimation, 240);
- Timeline.SetDesiredFrameRate(widthAnimation, 240);
-
- Storyboard.SetTarget(rotateAnimation, ImageSettings);
- Storyboard.SetTargetProperty(rotateAnimation, new PropertyPath("(UIElement.RenderTransform).(RotateTransform.Angle)"));
-
- storyboard.Children.Add(rotateAnimation);
- storyboard.Begin();
- SettingsMenu.BeginAnimation(WidthProperty, widthAnimation);
- });
+ DoubleAnimation rotateAnimation = new DoubleAnimation()
+ {
+ From = 0.0,
+ To = 360,
+ EasingFunction = new QuadraticEase(),
+ SpeedRatio = 2.0,
+ Duration = TimeSpan.FromSeconds(1)
+ };
+
+ DoubleAnimation widthAnimation = new DoubleAnimation()
+ {
+ From = SettingsMenu.Width != 400 ? 0 : 400,
+ To = SettingsMenu.Width != 400 ? 400 : 0,
+ EasingFunction = new QuadraticEase(),
+ SpeedRatio = 2.0,
+ Duration = TimeSpan.FromSeconds(1)
+ };
+
+ Timeline.SetDesiredFrameRate(rotateAnimation, 240);
+ Timeline.SetDesiredFrameRate(widthAnimation, 240);
+
+ Storyboard.SetTarget(rotateAnimation, ImageSettings);
+ Storyboard.SetTargetProperty(rotateAnimation, new PropertyPath("(UIElement.RenderTransform).(RotateTransform.Angle)"));
+
+ storyboard.Children.Add(rotateAnimation);
+ storyboard.Begin();
+ SettingsMenu.BeginAnimation(WidthProperty, widthAnimation);
}
private void SettingsMenu_QueryCursor(object sender, QueryCursorEventArgs e)
@@ -114,7 +111,7 @@ namespace GTweak
if (SystemDiagnostics.IsNeedUpdate && SettingsEngine.IsUpdateCheckRequired)
{
await Task.Delay(500);
- new UpdateWindow().ShowDialog();
+ Dispatcher.Invoke(() => new UpdateWindow().ShowDialog());
}
}));
new TypewriterAnimation(UtilityTitle.Text, UtilityTitle, TimeSpan.FromSeconds(0.4));
diff --git a/.Source/GTweak/Windows/NotificationWindow.xaml.cs b/.Source/GTweak/Windows/NotificationWindow.xaml.cs
index 2dcb2068..0372c1b9 100644
--- a/.Source/GTweak/Windows/NotificationWindow.xaml.cs
+++ b/.Source/GTweak/Windows/NotificationWindow.xaml.cs
@@ -9,7 +9,6 @@ using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media.Animation;
-using System.Windows.Threading;
namespace GTweak.Windows
{
@@ -54,28 +53,25 @@ namespace GTweak.Windows
notificationSound.Play();
}
- Dispatcher.Invoke(() =>
- {
- Rect primaryMonitorArea = SystemParameters.WorkArea;
-
- Top = primaryMonitorArea.Bottom - Height - 10;
- Left = primaryMonitorArea.Right - Width - 10;
+ Rect primaryMonitorArea = SystemParameters.WorkArea;
- DoubleAnimationUsingKeyFrames doubleAnimKeyFrames = new DoubleAnimationUsingKeyFrames();
+ Top = primaryMonitorArea.Bottom - Height - 10;
+ Left = primaryMonitorArea.Right - Width - 10;
- doubleAnimKeyFrames.KeyFrames.Add(new EasingDoubleKeyFrame(primaryMonitorArea.Right, TimeSpan.Zero)
- {
- EasingFunction = new QuadraticEase()
- });
- doubleAnimKeyFrames.KeyFrames.Add(new EasingDoubleKeyFrame(primaryMonitorArea.Right - Width - 10, KeyTime.FromTimeSpan(TimeSpan.FromMilliseconds(200)))
- {
- EasingFunction = new QuadraticEase()
- });
+ DoubleAnimationUsingKeyFrames doubleAnimKeyFrames = new DoubleAnimationUsingKeyFrames();
- Timeline.SetDesiredFrameRate(doubleAnimKeyFrames, 240);
- BeginAnimation(Canvas.LeftProperty, doubleAnimKeyFrames);
- BeginAnimation(OpacityProperty, FadeAnimation.FadeIn(1, 0.25));
+ doubleAnimKeyFrames.KeyFrames.Add(new EasingDoubleKeyFrame(primaryMonitorArea.Right, TimeSpan.Zero)
+ {
+ EasingFunction = new QuadraticEase()
});
+ doubleAnimKeyFrames.KeyFrames.Add(new EasingDoubleKeyFrame(primaryMonitorArea.Right - Width - 10, KeyTime.FromTimeSpan(TimeSpan.FromMilliseconds(200)))
+ {
+ EasingFunction = new QuadraticEase()
+ });
+
+ Timeline.SetDesiredFrameRate(doubleAnimKeyFrames, 240);
+ BeginAnimation(Canvas.LeftProperty, doubleAnimKeyFrames);
+ BeginAnimation(OpacityProperty, FadeAnimation.FadeIn(1, 0.25));
}
private void Window_Closing(object sender, CancelEventArgs e)