例如游戏战场 3。文件名为 bf3.exe 我希望我的应用程序能够检测到我第一次运行游戏的时间以及退出游戏的时间。
我在我的 Form1 中做了:
private ProcessStartInfo bf3;
在构造函数中:
bf3 = new ProcessStartInfo("bf3.exe");
我不确定使用 ProcessStartInfo 是否是个好主意以及下一步该做什么。
编辑:
这是我现在的代码:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
using DannyGeneral;
namespace CpuUsage
{
public partial class Form1 : Form
{
private DateTime dt;
private DateTime dt1;
private PerformanceCounter theCPUCounter;
private PerformanceCounter theMemCounter;
private PerformanceCounter specProcessCPUCounter;
private float cpuUsage;
private float memUsage;
private List<float> Values;
public Form1()
{
InitializeComponent();
isProcessRunning();
dt = DateTime.Now;
Values = new List<float>();
theCPUCounter = new PerformanceCounter("Processor", "% Processor Time", "_Total");
theMemCounter = new PerformanceCounter("Memory", "Available MBytes");
specProcessCPUCounter = new PerformanceCounter("Process", "% Processor Time", Process.GetCurrentProcess().ProcessName);
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void timer1_Tick(object sender, EventArgs e)
{
memUsage = theMemCounter.NextValue();
label1.Text = memUsage.ToString();
Logger.Write("Memory Usage " + memUsage.ToString());
cpuUsage = this.theCPUCounter.NextValue();
label2.Text = cpuUsage.ToString();
Logger.Write("Cpu Usage " + this.cpuUsage.ToString());
Values.Add(cpuUsage);
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
dt1 = DateTime.Now;
float Maximum = Values.Max();
float Minimum = Values.Min();
float Average = Values.Average();
string t = string.Format("Maximum --- {0} , Minimum --- {1} , Average --- {2}", Maximum, Minimum, Average);
Logger.Write(t);
TimeSpan ts = (dt1 - dt);
string time = ts.ToString(@"hh\:mm\:ss");
Logger.Write("Time The Program Was Running --- " + time);
}
private void isProcessRunning()
{
while (true)
{
Process[] proclist = Process.GetProcessesByName("bf3.exe");
if (proclist.Length > 0)
{
Logger.Write("Battlefield 3 Started");
}
else
{
Logger.Write("Battlefield 3 Exited");
}
}
}
}
}
现在的问题是它进入了while循环并且永远不会做它停留在循环中的计时器。我也需要使用计时器代码,同时检查/等待以查看 bf3.exe 是否启动或结束。