Implementation ideas:
At the beginning of the Main () method, traverse all processes and obtain the Assembly GUID and PID of each process. If a process with the same GUID and different PID is found, log out of the process.
Note:
1. GUID is used to ensure the reliability of determination as much as possible. The process name is too unreliable. In addition, the Assembly GUID is generated when a project is created and does not change with the version or content. Therefore, unless manually modified, the GUID remains the same when the project is compiled several times, it is not suitable for determining the Assembly identity. In addition to the question, the mutex method is widely used on the Internet. GUID is also recommended for mutex names;
2. The reason for adding the process ID is that the traversal process already contains its own process, so you must exclude itself;
3. Access to the MainModule attribute of some processes will cause an exception, so try-catch is used to skip these processes;
4. Only programs written in C # Can Get The GUID (a bit nonsense ~), But this is enough
5. Exit itself. Here we use Environment. exit () method, Application. the Exit () method does not work, and the program will still Run. I guess the reason is that the Application has not Run, so the Exit cannot be ~ (Younger brother's entry level, many things can only be turned around ~ Oh, no, it's a hyphen)
6. I wrote a blog in cnblogs for the first time. I hope you will give me more advice ~ Less bricks
1 using System;
2 using System. Diagnostics;
3 using System. Reflection;
4 using System. Runtime. InteropServices;
5 using System. Windows. Forms;
6
7 namespace TestCallAPIRefreshPolicy
8 {
9 static class Program
10 {
11 [STAThread]
12 static void Main ()
13 {
14 Guid ownGUID = new Guid (GuidAttribute) Attribute. GetCustomAttribute (Assembly. GetExecutingAssembly (), typeof (GuidAttribute). Value );
15 Guid proGUID;
16 int ownPID = Process. GetCurrentProcess (). Id;
17 int proPID;
18
19 foreach (Process p in Process. GetProcesses ())
20 {
21 try
22 {
23 proGUID = new Guid (GuidAttribute) Attribute. GetCustomAttribute (Assembly. LoadFile (p. MainModule. FileName), typeof (GuidAttribute). Value );
24 proPID = p. Id;
25 if (proGUID. Equals (ownGUID) & proPID! = OwnPID)
26 {
27 MessageBox. Show ("the program is running ");
28 Environment. Exit (Environment. ExitCode );
29}
30}
31 catch
32 {
33. continue; // skip the process if a process access exception occurs.
34}
35}
36
37 // if not Exit, start normally
38 Application. EnableVisualStyles ();
39 Application. SetCompatibleTextRenderingDefault (false );
40 Application. Run (new FmMain ());
41}
42}
43}
From ahdung