我无法在 Visual C# 中创建一个简单的应用程序,该应用程序执行以下操作:
- 坚持寻求一个具体的过程。
- 当该进程开始运行时,将资源复制到文件夹中。
- 当该过程结束时,将另一个资源复制到该文件夹。
我尝试使用计时器+线程,但没有成功。我认为 BackgroundWorker 在这里会有所帮助,但文档还不清楚。这是我当前的代码:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Resources;
using System.Text;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace ResourceCopyApp
{
public partial class MainWindow : Window {
BackgroundWorker bw;
bool pcRunning = false;
public MainWindow() {
InitializeComponent();
bw = new BackgroundWorker();
bw.DoWork += new DoWorkEventHandler(Loop);
bw.RunWorkerAsync();
}
private void Window_Loaded(object sender, RoutedEventArgs e) {
cfgInstall.Text = Properties.Settings.Default.pcLocation;
cfgLag.Value = Properties.Settings.Default.lag;
}
private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e) {
Properties.Settings.Default.pcLocation = cfgInstall.Text;
Properties.Settings.Default.lag = (int)cfgLag.Value;
Properties.Settings.Default.Save();
}
public void Loop(object sender, DoWorkEventArgs e) {
pcRunning = false;
bool pcWasRunning = pcRunning;
if (pcRunning && !pcWasRunning) {
MessageBox.Show("Process found");
pcWasRunning = true;
Swap(true);
}
foreach (Process p in Process.GetProcesses()) {
if (p.ProcessName.Equals("Process")) {
pcRunning = true;
}
}
if (!pcRunning && pcWasRunning) {
MessageBox.Show("Process lost");
Swap(false);
}
}
public void Swap(bool v) {
byte[] file;
Thread.Sleep(new TimeSpan((long)cfgLag.Value));
if (v) {
file = Properties.Resources.NewRes;
} else {
file = Properties.Resources.BackupRes;
}
string path = cfgInstall.Text;
if (!cfgInstall.Text.EndsWith("/") && !cfgInstall.Text.EndsWith("\\")) {
path = cfgInstall.Text + "/test.txt";
}
File.WriteAllBytes(path, file);
}
}
}