如何检查我的C#Windows应用程序是否正在运行?
我知道我可以检查进程名称,但如果exe更改,则可以更改名称。
有没有办法让哈希键或其他东西让我的应用程序与众不同?
答案 0 :(得分:38)
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("name of application.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);
}
}
答案 1 :(得分:21)
推荐的方法是使用互斥锁。你可以在这里看看样品: http://www.codeproject.com/KB/cs/singleinstance.aspx
具体代码:
///
/// check if given exe alread running or not
///
/// returns true if already running
private static bool IsAlreadyRunning()
{
string strLoc = Assembly.GetExecutingAssembly().Location;
FileSystemInfo fileInfo = new FileInfo(strLoc);
string sExeName = fileInfo.Name;
bool bCreatedNew;
Mutex mutex = new Mutex(true, "Global\\"+sExeName, out bCreatedNew);
if (bCreatedNew)
mutex.ReleaseMutex();
return !bCreatedNew;
}
答案 2 :(得分:1)
对于我的WPF应用程序,我已经定义了全局应用程序ID并使用信号量来处理它。
public partial class App : Application
{
private const string AppId = "c1d3cdb1-51ad-4c3a-bdb2-686f7dd10155";
//Passing name associates this sempahore system wide with this name
private readonly Semaphore instancesAllowed = new Semaphore(1, 1, AppId);
private bool WasRunning { set; get; }
private void OnExit(object sender, ExitEventArgs e)
{
//Decrement the count if app was running
if (this.WasRunning)
{
this.instancesAllowed.Release();
}
}
private void OnStartup(object sender, StartupEventArgs e)
{
//See if application is already running on the system
if (this.instancesAllowed.WaitOne(1000))
{
new MainWindow().Show();
this.WasRunning = true;
return;
}
//Display
MessageBox.Show("An instance is already running");
//Exit out otherwise
this.Shutdown();
}
}
答案 3 :(得分:0)
你需要一种方式从应用程序说“我正在运行”,
1)打开WCF ping服务 2)在启动时写入注册表/文件,在关闭时删除 3)创建一个Mutex
...我更喜欢WCF部分,因为您可能无法正确清理文件/注册表,而Mutex似乎也有自己的问题
答案 4 :(得分:0)
在我的情况下,Mutex和Semaphore无效(我按照建议尝试了它们,但是在我开发的应用程序中却没有达到目的)。经过稍作修改后,abramlimpin提供的答案对我有用。
这就是我最终使它工作的方式。 首先,我创建了一些辅助函数:
public static class Ext
{
private static string AssemblyFileName(this Assembly myAssembly)
{
string strLoc = myAssembly.Location;
FileSystemInfo fileInfo = new FileInfo(strLoc);
string sExeName = fileInfo.Name;
return sExeName;
}
private static int HowManyTimesIsProcessRunning(string name)
{
int count = 0;
name = name.ToLowerInvariant().Trim().Replace(".exe", "");
foreach (Process clsProcess in Process.GetProcesses())
{
var processName = clsProcess.ProcessName.ToLowerInvariant().Trim();
// System.Diagnostics.Debug.WriteLine(processName);
if (processName.Contains(name))
{
count++;
};
};
return count;
}
public static int HowManyTimesIsAssemblyRunning(this Assembly myAssembly)
{
var fileName = AssemblyFileName(myAssembly);
return HowManyTimesIsProcessRunning(fileName);
}
}
然后,我在 main 方法中添加了以下内容:
[STAThread]
static void Main()
{
const string appName = "Name of your app";
// Check number of instances running:
// If more than 1 instance, cancel this one.
// Additionally, if it is the 2nd invocation, show a message and exit.
var numberOfAppInstances = Assembly.GetExecutingAssembly().HowManyTimesIsAssemblyRunning();
if (numberOfAppInstances == 2)
{
MessageBox.Show("The application is already running!
+"\nClick OK to close this dialog, then switch to the application by using WIN + TAB keys.",
appName, MessageBoxButtons.OK, MessageBoxIcon.Warning);
};
if (numberOfAppInstances >= 2)
{
return;
};
}
如果您第三次,第四次调用该应用程序,它将不再显示警告,而是立即退出。
答案 5 :(得分:-1)
结帐:What is a good pattern for using a Global Mutex in C#?
// unique id for global mutex - Global prefix means it is global to the machine
const string mutex_id = "Global\\{B1E7934A-F688-417f-8FCB-65C3985E9E27}";
static void Main(string[] args)
{
using (var mutex = new Mutex(false, mutex_id))
{
// edited by Jeremy Wiebe to add example of setting up security for multi-user usage
// edited by 'Marc' to work also on localized systems (don't use just "Everyone")
var allowEveryoneRule = new MutexAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), MutexRights.FullControl, AccessControlType.Allow);
var securitySettings = new MutexSecurity();
securitySettings.AddAccessRule(allowEveryoneRule);
mutex.SetAccessControl(securitySettings);
//edited by acidzombie24
var hasHandle = false;
try
{
try
{
// note, you may want to time out here instead of waiting forever
//edited by acidzombie24
//mutex.WaitOne(Timeout.Infinite, false);
hasHandle = mutex.WaitOne(5000, false);
if (hasHandle == false) return;//another instance exist
}
catch (AbandonedMutexException)
{
// Log the fact the mutex was abandoned in another process, it will still get aquired
}
// Perform your work here.
}
finally
{
//edit by acidzombie24, added if statemnet
if (hasHandle)
mutex.ReleaseMutex();
}
}
}
答案 6 :(得分:-1)
更难的方法是打开一些进程间通信或套接字,因此使用进程列表可以查询每个进程以查看它是否是您的应用程序。
答案 7 :(得分:-1)
在装配数据中输入guid。 将此guid添加到注册表。 输入一个reg键,应用程序读取它自己的名称,并在那里添加名称作为值。
另一个任务监视器读取reg密钥并知道应用程序名称。
答案 8 :(得分:-1)
您可以简单地使用varialbles和一个文件来检查程序的运行情况。 当打开文件包含值时,程序关闭时将此值更改为另一个值。