环境:C#,IDE:Visual Studio 2017
我想知道xyz.exe应用程序是否在当前登录用户的计算机上运行。
例如:
计算机中有2个用户-用户:A(管理员用户)和用户:B(非管理员用户)
用户A登录到计算机并运行xyz.exe应用程序并执行会话锁定操作。
用户B现在已使用其帐户登录。 (用户A尚未注销,但他/她仍已登录但其会话已锁定)
用户A正在运行xyz.exe应用程序,但是对于用户B,xyz.exe应用程序未运行。
我想知道xyz.exe应用程序是否正在为用户B运行。是否可以这样做,如果可以,怎么办?
我还更新了xyz.exe,它是从以下位置的窗口注册表中运行的路径:Computer \ HKEY_LOCAL_MACHINE \ SOFTWARE \ Microsoft \ Windows \ CurrentVersion \ Run 这样,一旦任何用户注销,登录后xyz.exe就会自动开始运行(这是我的项目的要求之一)。
以下代码有效:
/// <summary>
/// Declaring Mutex
/// </summary>
private Mutex _mutex = null;
/// <summary>
/// To check if any other instance of xyz.exe is running
/// </summary>
private bool IsSingleInstanceRunning()
{
// To check if any other instance of xyz.exe is running for currently logged-in user
_mutex = new Mutex(true, Process.GetCurrentProcess().ProcessName + Environment.UserName, out bool isSingleInstanceRunning);
// Return true if no instance of xyz.exe is running in task manager for current logged-in user.
// Return false if multiple instances of xyz.exe is running in task manager for current logged-in user.
return isSingleInstanceRunning;
}
/// <summary>
/// Entry point of application xyz.exe
/// </summary>
public void ApplicationStartup()
{
if (!IsSingleInstanceRunning())
{
System.Environment.Exit(0);
}
// Release Mutex once application is launched
_mutex.ReleaseMutex();
// Keeping mutex object alive for not creating multiple instances for multiple users
GC.KeepAlive(_mutex);
// Logic to start application xyz.exe
}
答案 0 :(得分:0)