-
Notifications
You must be signed in to change notification settings - Fork 0
/
Program.cs
107 lines (84 loc) · 3.34 KB
/
Program.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
using System;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Windows.Forms;
namespace wyUpdate
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static int Main(string[] args)
{
Application.EnableVisualStyles();
frmMain mainForm = new frmMain(args);
// if the mainForm has been closed, return the code
if (mainForm.IsDisposed)
return mainForm.ReturnCode;
StringBuilder mutexName = new StringBuilder("Local\\wyUpdate-" + mainForm.update.GUID);
if (mainForm.IsAdmin)
mutexName.Append('a');
if (mainForm.SelfUpdateState == SelfUpdateState.FullUpdate)
mutexName.Append('s');
if (mainForm.IsNewSelf)
mutexName.Append('n');
Mutex mutex = new Mutex(true, mutexName.ToString());
if (mutex.WaitOne(TimeSpan.Zero, true))
{
Application.Run(mainForm);
mutex.ReleaseMutex();
}
else
{
FocusOtherProcess();
return 4;
}
/*
Possible return codes:
0 = Success / no updates found
1 = General error
2 = Updates found
3 = Update process cancelled
4 = wyUpdate exited immediately to focus another wyUpdate instance
*/
return mainForm.ReturnCode;
}
[DllImport("user32")]
static extern bool SetForegroundWindow(IntPtr hWnd);
[DllImport("user32")]
static extern int ShowWindow(IntPtr hWnd, int swCommand);
[DllImport("user32")]
static extern bool IsIconic(IntPtr hWnd);
public static void FocusOtherProcess()
{
Process proc = Process.GetCurrentProcess();
// Using Process.ProcessName does not function properly when
// the actual name exceeds 15 characters. Using the assembly
// name takes care of this quirk and is more accurate than
// other work arounds.
string assemblyName = Assembly.GetExecutingAssembly().GetName().Name;
foreach (Process otherProc in Process.GetProcessesByName(assemblyName))
{
//ignore "this" process, and ignore wyUpdate with a different filename
if (proc.Id != otherProc.Id
&& otherProc.MainModule != null && proc.MainModule != null
&& proc.MainModule.FileName == otherProc.MainModule.FileName)
{
// Found a "same named process".
// Assume it is the one we want brought to the foreground.
// Use the Win32 API to bring it to the foreground.
IntPtr hWnd = otherProc.MainWindowHandle;
if (IsIconic(hWnd))
ShowWindow(hWnd, 9); //SW_RESTORE
SetForegroundWindow(hWnd);
break;
}
}
}
}
}