Three of my previous articles were found on the Internet (link below), which is a function that implements the program only once.
C # prevents programs from running multiple times
A function that the C # detector runs repeatedly (can be detected in multi-user logins)
The C # Implementation program starts only once (runs multiple times to activate the first instance, giving it the focus and displaying it at the front end)
C # Implementation program starts only once (implements program self-restart)
If you have read the previous articles, I believe you may already have the answer, I used to feel there are some differences, and now I summarize the record:
One: Using the System.Threading.Mutex class
Using this method, I test it myself and use it when a single user of Windows can use it, and when multiple Windows users are using it, it is not possible to detect whether the program is running.
Second: Check the process name
Process[] processes = Process.getprocessesbyname (Process.getcurrentprocess (). ProcessName);
You can use this method to check all the process names on the current machine, and multiple users can also detect them at the same time. However, if the program is renamed to run, it cannot detect whether the program is in a running state.
Three: Using the API
API one: [DllImport ("User32.dll")] private static extern bool Showwindowasync (IntPtr hWnd, int cmdshow); [DllImport ("User32.dll")] private static extern bool SetForegroundWindow (IntPtr hWnd);
API two: [DllImport ("Kernel32.dll", CharSet = CharSet.Auto)] private static extern IntPtr OpenMutex ( UINT dwDesiredAccess,//access int binherithandle, //inheritance option string lpname //object name ); [DllImport ("Kernel32.dll", CharSet = CharSet.Auto)] private static extern IntPtr CreateMutex ( IntPtr lpmutexattributes,//SD int Binitialowner, //Initial Owner String lpname //object name );
This method has been mentioned in my previous article about the use of two types of APIs
API one, you can make the program front-end display, and get the focus.
API two, actually more like the System.Threading.Mutex class,
Because these features are not used temporarily in the project, there is not much comment.
C # Implementation program starts only once (summary)