我不是一个经验丰富的程序员,所以任何建议/指导/示例都将不胜感激!我在C#(.Net framework 4.5)中有一个windows窗体应用程序,它正在替换一个windows服务(遇到了Session0变量的问题)。应用程序需要打开一个进程(我将使用Notepad作为示例),并每隔5分钟检查Notepad是否仍然打开。如果记事本未打开,则表单应用程序必须打开它的一个实例。如果记事本已打开,则该应用程序必须阻止用户打开另一个记事本实例。我的编码当前关闭了Notepad的所有实例。我只需要应用程序来停止要打开的Notepad的第二个实例。问题是,用户根本不允许与应用程序交互,正如你在编码中所注意到的,用户甚至看不到表单
private void Form1_Load(object sender, EventArgs e)
{
this.ShowInTaskbar = false;
this.Visible = false;
//handle Elapsed event
myTimer.Tick += new EventHandler(OnElapsedTime);
//This statement is used to set interval to 5 minute (= 300,000 milliseconds)
myTimer.Interval = 60000;//300000;
//enabling the timer
myTimer.Enabled = true;
WatchForProcessStart("Notepad.exe");
}
private void OnElapsedTime(object source, EventArgs e)
{
bool status = IsProcessOpen("notepad");
if (status == true)
{
//TraceService("Notepad is already open" + DateTime.Now);
}
else
{
Process process = new Process();
process.StartInfo.FileName = "notepad.exe";
process.EnableRaisingEvents = true;
process.StartInfo.WindowStyle = ProcessWindowStyle.Normal;
process.Start();
//TraceService("Notepad opened" + DateTime.Now);
}
}
public bool IsProcessOpen(string procName)
{
System.Diagnostics.Process[] proc = System.Diagnostics.Process.GetProcessesByName(procName);
if (proc.Length > 0)
{
return true;
}
else
{
return false;
}
}
private ManagementEventWatcher WatchForProcessStart(string processName)
{
string queryString =
"SELECT TargetInstance" +
" FROM __InstanceCreationEvent " +
"WITHIN 10 " +
" WHERE TargetInstance ISA 'Win32_Process' " +
" AND TargetInstance.Name = '" + processName + "'";
// The dot in the scope means use the current machine
string scope = @"\.rootCIMV2";
// Create a watcher and listen for events
ManagementEventWatcher watcher = new ManagementEventWatcher(scope, queryString);
watcher.EventArrived += ProcessStarted;
watcher.Start();
return watcher;
}
private void ProcessStarted(object sender, EventArrivedEventArgs e)
{
ManagementBaseObject targetInstance = (ManagementBaseObject)e.NewEvent.Properties["TargetInstance"].Value;
string processName = targetInstance.Properties["Name"].Value.ToString();
bool status = IsProcessOpen("notepad");
if (status == true)
{
System.Diagnostics.Process.Start("cmd.exe", "/c taskkill /IM notepad.exe");
}
else
{
Process process = new Process();
process.StartInfo.FileName = "notepad.exe";
process.EnableRaisingEvents = true;
process.StartInfo.WindowStyle = ProcessWindowStyle.Normal;
process.Start();
}
}
将其封装在Mutex 中
var mutexId = "MyApplication";
using (var mutex = new Mutex(false, mutexId))
{
if (!mutex.WaitOne(0, false))
{
MessageBox.Show("Only one instance of the application is allowed!", "Info", MessageBoxButtons.OK, MessageBoxIcon.Hand);
return;
}
// Do scome work
}
如果您想将其限制为每台机器一个实例,则mutex Id需要以Global\