How to make your own program only run once

xiaoxiao2021-03-17  186

I introduce two mainstream methods.

Method 1: Use MUTEX to do

1. First add the following Namespace:

Using system.threading;

2. Modify the system main function, which is approximately 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 you encode above, you should pay attention to it. When you give Mutex, don't be too simple to prevent MUTEX repetitions with other programs, so that the expected effect is not possible.

Method 2: Using Process

1. First add the following Namespace:

Using system.diagnostics;

Using system.reflection;

2. Add the following functions:

Public Static Process RunningInstance ()

{

Process Current = process.getcurrentProcess ();

Process [] processes = process.getProcesSbyName (current.ProcessName);

// Loop through the running processs in with the Same Name

Foreach (Process Process In Processes)

{

// ignore the current process

IF (Process.id! = 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, which is approximately as follows:

IF (RunningInstance () == NULL)

Application.run (New YourFormName ());

As can be encoded above, it is to note that it is optional to determine if the code is equal to whether the process module file name is equal. If the current program only exists in the file system, the above method is possible; otherwise do not delete this part of the code.

转载请注明原文地址:https://www.9cbs.com/read-129724.html

New Post(0)