I will introduce two mainstream methods. Method 1: Use mutex for 1. first, add the following namespace: using system. threading; 2. modify the main function of the system as follows: bool bcreatednew; // create a new mutex using specific mutex name mutex M = new mutex (false, "myuniquename", out bcreatednew ); if (bcreatednew) application. run (New yourformname (); if it is encoded above, note that it is not too simple to name mutex, to prevent repeated mutex with other programs and thus fail to achieve the expected results. Method 2: Use process for 1. first, add the following namespace: using system. diagnostics; using system. reflection; 2. add the following function: public static process runninginstance () {process current = process. getcurrentprocess (); Process [] processes = process. getprocessesbyname (current. processname); // loop through the running processes in with the same name foreach (Process in processes) {// ignore the current process if (process. I D! = Current. ID) {// make sure that the process is running from the EXE file. if (assembly. getexecutingassembly (). location. replace ("/", "//") = current. mainmodule. filename) {// return the other process instance. return process; }}// no other instance was found, return null. return NULL;} 3. modify the system main function as follows: If (runninginstance () = NULL) application. run (New yourformname (); for example, you can encode the code above. Note that when judging Optional. If only one program exists in the file system, the above method is acceptable; otherwise, do not delete this part of code. Compared with the two methods, in terms of efficiency and simplicity, the former method is the best and I like it. The latter method is slow, secondly, we use processname to search for the process in the system. It is possible that the process is not what I want. Although the file directory is added to the end to judge the process, but it contains potential problems (as mentioned above ). However, the first method also has a defect, that is, the scalability operation is inconvenient. For example, if the program runs only once, it is popped up and displayed to the beginning. The latter method is advantageous.
The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion;
products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the
content of the page makes you feel confusing, please write us an email, we will handle the problem
within 5 days after receiving your email.
If you find any instances of plagiarism from the community, please send an email to:
info-contact@alibabacloud.com
and provide relevant evidence. A staff member will contact you within 5 working days.