using BOB; using MahApps.Metro.Controls; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.IO; using System.Reflection.Metadata; using System.Windows; using System.Windows.Controls; using System.Windows.Input; using System.Windows.Threading; namespace ProcessManager.ViewModels { public class PMainViewModel:BindableBase { private ObservableCollection _configList; public ObservableCollection ConfigList { get => _configList; set => SetProperty(ref _configList, value); } private readonly IDialogService _dialogService; private Dictionary ProcessDic { get; set; } = new Dictionary(); public ICommand StartCommand { get; set; } public ICommand EditCommand { get; set; } public ICommand WindowLoadedCommand { get; set; } public PMainViewModel(IDialogService dialogService) { _dialogService = dialogService; EditCommand=new DelegateCommand(OnEdit); StartCommand = new DelegateCommand(OnStart); WindowLoadedCommand = new DelegateCommand(OnWindowLoaded); } private void OnWindowLoaded() { if (ConfigList != null) ConfigList.Clear(); var JSONFiles = Directory.GetFiles(JsonHelper.SystemPath, "*.json"); foreach(var file in JSONFiles) { JsonHelper.ConfigFile = file; var config = JsonHelper.LoadFromFile(); if(ConfigList==null) { ConfigList = new ObservableCollection(); } ConfigList.Add(config); } } private void OnStart(string deviceName) { if (ProcessDic.ContainsKey(deviceName)) { MessageBox.Show("进程已启动"); return; } try { string currentDir = Environment.CurrentDirectory; string exePath = Path.Combine(currentDir, "BOB.exe"); if (!File.Exists(exePath)) { MessageBox.Show($"未找到文件: {exePath}"); return; } ProcessStartInfo startInfo = new ProcessStartInfo { FileName = exePath, Arguments = deviceName, UseShellExecute = true }; var configToSave = ConfigList.FirstOrDefault(x => x.Title == deviceName); if (configToSave != null) { JsonHelper.ConfigFile = Path.Combine(JsonHelper.SystemPath, $"{deviceName}.json"); JsonHelper.SaveToFile(configToSave); } var process = Process.Start(startInfo); process.EnableRaisingEvents = true; process.Exited += (s, args) => { ProcessDic.Remove(deviceName); Application.Current.Dispatcher.Invoke(() => { OnWindowLoaded(); }); }; ProcessDic.Add(deviceName, process); } catch (Exception ex) { MessageBox.Show($"启动失败: {ex.Message}"); } } private void OnEdit(string deviceName) { if (ProcessDic.ContainsKey(deviceName)) { MessageBox.Show("请先关闭进程再进行编辑"); return; } JsonHelper.ConfigFile = Path.Combine(JsonHelper.SystemPath, $"{deviceName}.json"); var ConfigSystem = JsonHelper.LoadFromFile(); var parameters = new DialogParameters { { "SystemConfig", ConfigSystem }, { "Title", deviceName } }; _dialogService.ShowDialog("Setting", parameters, r => { if (r.Result == ButtonResult.OK) { // 用户点击 OK } }); } } }