1 | using System;
|
---|
2 | using System.Diagnostics;
|
---|
3 | using System.Management;
|
---|
4 | using System.Security.Principal;
|
---|
5 | using System.Windows.Forms;
|
---|
6 | using HeuristicLab.Clients.Hive.SlaveCore.Views;
|
---|
7 |
|
---|
8 | namespace HeuristicLab.Clients.Hive.SlaveCore.SlaveTrayIcon {
|
---|
9 | static class Program {
|
---|
10 | /// <summary>
|
---|
11 | /// The main entry point for the application.
|
---|
12 | /// </summary>
|
---|
13 | [STAThread]
|
---|
14 | static void Main() {
|
---|
15 | KillOtherInstances();
|
---|
16 |
|
---|
17 | Application.EnableVisualStyles();
|
---|
18 | Application.SetCompatibleTextRenderingDefault(false);
|
---|
19 | MainWindow mw = new MainWindow();
|
---|
20 | mw.MinimizeToTray();
|
---|
21 | mw.Content = new SlaveItem();
|
---|
22 |
|
---|
23 | Application.Run();
|
---|
24 | }
|
---|
25 |
|
---|
26 | /// <summary>
|
---|
27 | /// Gets the owner of a process
|
---|
28 | /// (based on http://www.codeproject.com/KB/cs/processownersid.aspx)
|
---|
29 | /// </summary>
|
---|
30 | public static string GetProcessOwner(int pid) {
|
---|
31 | string ownerSID = String.Empty;
|
---|
32 | string processName = String.Empty;
|
---|
33 | try {
|
---|
34 | ObjectQuery sq = new ObjectQuery
|
---|
35 | ("Select * from Win32_Process Where ProcessID = '" + pid + "'");
|
---|
36 | ManagementObjectSearcher searcher = new ManagementObjectSearcher(sq);
|
---|
37 | if (searcher.Get().Count == 0)
|
---|
38 | return ownerSID;
|
---|
39 | foreach (ManagementObject oReturn in searcher.Get()) {
|
---|
40 | string[] sid = new String[1];
|
---|
41 | oReturn.InvokeMethod("GetOwnerSid", (object[])sid);
|
---|
42 | ownerSID = sid[0];
|
---|
43 | return ownerSID;
|
---|
44 | }
|
---|
45 | }
|
---|
46 | catch {
|
---|
47 | return ownerSID;
|
---|
48 | }
|
---|
49 | return ownerSID;
|
---|
50 | }
|
---|
51 |
|
---|
52 | /// <summary>
|
---|
53 | /// kill all other slave tray icons, we only want 1 running at a time
|
---|
54 | /// (and if a newer version is installed the older one should be killed)
|
---|
55 | /// </summary>
|
---|
56 | private static void KillOtherInstances() {
|
---|
57 | String currentUserSID = WindowsIdentity.GetCurrent().User.Value;
|
---|
58 | Process curProc = Process.GetCurrentProcess();
|
---|
59 |
|
---|
60 | try {
|
---|
61 | Process[] procs = Process.GetProcessesByName(curProc.ProcessName);
|
---|
62 | foreach (Process p in procs) {
|
---|
63 | if (p.Id != curProc.Id) {
|
---|
64 | String procUserSID = GetProcessOwner(p.Id);
|
---|
65 | if (procUserSID == currentUserSID) {
|
---|
66 | p.Kill();
|
---|
67 | }
|
---|
68 | }
|
---|
69 | }
|
---|
70 | }
|
---|
71 | catch (InvalidOperationException) { }
|
---|
72 | catch (Exception) {
|
---|
73 | MessageBox.Show("There is another instance of the Hive Slave tray icon running which can't be closed.", "HeuristicLab Hive Slave");
|
---|
74 | }
|
---|
75 | }
|
---|
76 | }
|
---|
77 | }
|
---|