如何以编程方式检查我的WPF应用程序是否正常运行?,与VB中的App.PrevInstance类似。 请建议我一个简单的方法,我是初学者。
这是我的代码,
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
var runningProcessByName = Process.GetProcessesByName("TCLCGFP");
if (runningProcessByName.Length == 0)
{
//Process.Start("TCLCGFP.exe");
new TraacsClcProcess();
}
else
{
MessageBox.Show("Application is already Running.","TCLCGFP",MessageBoxButton.OK,MessageBoxImage.Information);
}
Environment.Exit(0);
}
始终显示应用程序已在运行:P
答案 0 :(得分:2)
大多数人所做的是使用命名的Mutex对象。使用构造函数重载,该重载会告诉您是否已成功创建它以查明另一个进程是否已创建具有相同名称的进程。使用互斥锁的示例:
RendererThread
您还可以阅读此How to determine if a previous instance of my application is running?
答案 1 :(得分:0)
您可以检查我在评论中提供的链接中指定的流程名称:
public partial class App : System.Windows.Application
{
public bool IsProcessOpen(string name)
{
foreach (Process clsProcess in Process.GetProcesses()) {
if (clsProcess.ProcessName.Contains(name))
{
return true;
}
}
return false;
}
protected override void OnStartup(StartupEventArgs e)
{
// Get Reference to the current Process
Process thisProc = Process.GetCurrentProcess();
if (IsProcessOpen("TCLCGFP.exe") == false)
{
//System.Windows.MessageBox.Show("Application not open!");
//System.Windows.Application.Current.Shutdown();
}
else
{
// Check how many total processes have the same name as the current one
if (Process.GetProcessesByName(thisProc.ProcessName).Length > 1)
{
// If ther is more than one, than it is already running.
System.Windows.MessageBox.Show("Application is already running.");
System.Windows.Application.Current.Shutdown();
return;
}
base.OnStartup(e);
}
}