Friday, April 13, 2012

WPF : Determining if user is running same application instance on a terminal server

Please refer to this article in which I showed how we can determine if user is trying to run same application instance, this approach will work on single user Desktop machine, but it will not work when there are multiple users connecting to a terminal server and are trying to run same application. What happens is if a user start application, and then if some other user tries to start same application then it fails saying that application is already running because it doesn't distinguishes 2 users, so in this article I am going to show how we can change the old logic to consider individual user also.


private void Application_Startup(object sender, StartupEventArgs e)
{        
 string processname = Process.GetCurrentProcess().ProcessName + ".exe";
 string currentuserid = GetLoggedInUserName(); //This function should return Loggedin user name, you can put your logic here.
 totaluserapplicationinstance = 0;
 
 System.Management.ManagementObjectSearcher Processes = new System.Management.ManagementObject Searcher("SELECT * FROM Win32_Process Where Name ='" + processname + "'");
               
 foreach (System.Management.ManagementObject process in Processes.Get())
 {
  string[] OwnerInfo = new string[2];
  process.InvokeMethod("GetOwner", (object[])OwnerInfo);
  if (OwnerInfo[0].Equals(currentuserid))
  {
   totaluserapplicationinstance++;
  }
 }
 
 alreadyloggedin = totaluserapplicationinstance > 1;
 if (alreadyloggedin)
 {
  Messagebox.Show("You are already running an instance of same application");
  App.Current.Shutdown();
  return;
 }
}

No comments:

Post a Comment