[C #] can only run one instance of a program

Source: Internet
Author: User

C # implementations can only run one instance of the program (added in the form's Load event)

1. Only one instance of the program can be run according to the name limit

System.Diagnostics.Process Process = System.Diagnostics.Process.GetCurrentProcess (); system.diagnostics.process[] processlist = System.Diagnostics.Process.GetProcessesByName (Process. ProcessName); if (processlist.length! = 1) {System.Windows.Forms.MessageBox.Show ("This computer already has one program running.")    , "Warning", MessageBoxButtons.OK, messageboxicon.warning);     Application.exit (); Return }

2. Another way to run only one instance based on the name limit

String modelname = Process.getcurrentprocess (). Mainmodule.modulename; String processName = System.IO.Path.GetFileNameWithoutExtension (modelname); Process[] processes = Process.getprocessesbyname (processName);//Create a process resource array if (processes) based on the process name.     Length > 1) {MessageBox.Show ("The program is already running!", "hint", MessageBoxButtons.OK, MessageBoxIcon.Information); This.   Close (); }

3. Using mutex mutex implementation can only run one instance of the program

BOOL exit;       System.Threading.Mutex Newmutex = new System.Threading.Mutex (True, "once only", out exit); if (exit) {Newmutex.releasemutex ();//release mutex, you can run new form} else {Messageb Ox.        Show ("This program already has an instance running!", "hint", MessageBoxButtons.OK, MessageBoxIcon.Information); This.      Close (); }


This article from "Flower Blossom Fall" blog, declined reprint!

[C #] can only run one instance of a program

Contact Us

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.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.