using System.Collections.ObjectModel; using System.Diagnostics; using System.Windows.Input; using System.Windows.Threading; using SpdUp.Core; using SpdUp.Models; using SpdUp.Services; namespace SpdUp.ViewModels; /// /// Process Manager ViewModel. /// public sealed class ProcessManagerViewModel : ObservableObject { private readonly DispatcherTimer _refreshTimer; public ObservableCollection Processes { get; } = new(); private ProcessEntry? _selectedProcess; public ProcessEntry? SelectedProcess { get => _selectedProcess; set => SetProperty(ref _selectedProcess, value); } public ICommand RefreshCommand { get; } public ICommand KillProcessCommand { get; } public ICommand SetHighPriorityCommand { get; } public ICommand SetNormalPriorityCommand { get; } public ProcessManagerViewModel() { RefreshCommand = new RelayCommand(RefreshProcesses); KillProcessCommand = new RelayCommand(KillSelected, () => SelectedProcess is not null); SetHighPriorityCommand = new RelayCommand(() => SetPriority(ProcessPriorityClass.High), () => SelectedProcess is not null); SetNormalPriorityCommand = new RelayCommand(() => SetPriority(ProcessPriorityClass.Normal), () => SelectedProcess is not null); _refreshTimer = new DispatcherTimer { Interval = TimeSpan.FromSeconds(3) }; _refreshTimer.Tick += (_, _) => RefreshProcesses(); RefreshProcesses(); _refreshTimer.Start(); } private void RefreshProcesses() { var procs = Process.GetProcesses() .Select(p => { try { return new ProcessEntry { Pid = p.Id, Name = p.ProcessName, WindowTitle = string.IsNullOrWhiteSpace(p.MainWindowTitle) ? null : p.MainWindowTitle, MemoryMB = p.WorkingSet64 / 1048576f, PriorityClass = TryGetPriority(p), IsSystem = p.Id <= 4 }; } catch { return null; } finally { p.Dispose(); } }) .Where(e => e is not null) .OrderByDescending(e => e!.MemoryMB) .Take(200) .ToList(); Processes.Clear(); foreach (var p in procs) Processes.Add(p!); } private static string TryGetPriority(Process p) { try { return p.PriorityClass.ToString(); } catch { return "N/A"; } } private void KillSelected() { if (SelectedProcess is null) return; OptimizationService.KillProcess(SelectedProcess.Pid); RefreshProcesses(); } private void SetPriority(ProcessPriorityClass priority) { if (SelectedProcess is null) return; try { using var proc = Process.GetProcessById(SelectedProcess.Pid); proc.PriorityClass = priority; } catch { } RefreshProcesses(); } }