Implement the unique running instance C # code based on. NET platform applications

Source: Internet
Author: User
Main Code
Singleinstance. CS file,

Using system;
Using system. IO;
Using system. diagnostics;
Using system. Threading;
Using system. reflection;
Using system. runtime. interopservices;
Namespace zhengzuo. csharpcode
{
/// <Summary>
/// Start only one application Program Instance Control
/// </Summary>
Public static class singleinstance
{
Private const int ws_shownormal = 1;
[Dllimport ("user32.dll")]
Private Static extern bool showwindowasync (intptr hwnd, int cmdshow );
[Dllimport ("user32.dll")]
Private Static extern bool setforegroundwindow (intptr hwnd );
// Mark file name
Private Static string runflagfullname = NULL;
// Declare the synchronization primitive
Private Static mutex = NULL;

/// <Summary>
/// Static Constructor
/// </Summary>
Static singleinstance ()
{
}
# Region API implementation
/// <Summary>
/// Obtain the application process instance. If no matching process exists, null is returned.
/// </Summary>
/// <Returns> returns the current process instance </returns>
Public static process getrunninginstance ()
{
Process currentprocess = process. getcurrentprocess (); // obtain the current process
// Obtain the fully qualified name of the current running program
String currentfilename = currentprocess. mainmodule. filename;
// Obtain the process array named processname.
Process [] processes = process. getprocessesbyname (currentprocess. processname );
// Traverse processes with the same process name running
Foreach (Process in processes)
{
If (process. mainmodule. filename = currentfilename)
{
If (process. ID! = Currentprocess. ID) // exclude the current process based on the process ID
Return process; // return the running process instance.
}
}
Return NULL;
}
/// <Summary>
/// Obtain the application handle, set the foreground running of the application, and return the bool Value
/// </Summary>
Public static bool handlerunninginstance (process instance)
{
// Ensure that the window is not minimized or maximized
Showwindowasync (instance. main1_whandle, ws_shownormal );
// Set the actual routine to foreground window
Return setforegroundwindow (instance. main1_whandle );
}
/// <Summary>
/// Obtain the window handle, set the foreground running of the application, return the bool value, and reload the Method
/// </Summary>
/// <Returns> </returns>
Public static bool handlerunninginstance ()
{
PROCESS p = getrunninginstance ();
If (P! = NULL)
{
Handlerunninginstance (P );
Return true;
}
Return false;
}
# Endregion

# Region mutex implementation
/// <Summary>
/// Create the application process mutex
/// </Summary>
/// <Returns> the creation result is returned. "True" indicates that the creation is successful, and "false" indicates that the creation fails. </Returns>
Public static bool createmutex ()
{
Return createmutex (assembly. getentryassembly (). fullname );
}
/// <Summary>
/// Create the application process mutex
/// </Summary>
/// <Param name = "name"> mutex name </param>
/// <Returns> the creation result is returned. "True" indicates that the creation is successful, and "false" indicates that the creation fails. </Returns>
Public static bool createmutex (string name)
{
Bool result = false;
Mutex = new mutex (true, name, out result );
Return result;
}
/// <Summary>
/// Release mutex
/// </Summary>
Public static void releasemutex ()
{
If (mutex! = NULL)
{
Mutex. Close ();
}
}
# Endregion

# Region flag implementation
/// <Summary>
/// Initialize the program running flag. If it is set successfully, true is returned. If it is set to false, an exception is thrown if it fails to be set.
/// </Summary>
/// <Returns> return the setting result </returns>
Public static bool initrunflag ()
{
If (file. exists (runflag ))
{
Return false;
}
Using (filestream FS = new filestream (runflag, filemode. Create ))
{
}
Return true;
}
/// <Summary>
/// Release the initialization program running flag. If the release fails, an exception is thrown.
/// </Summary>
Public static void disposerunflag ()
{
If (file. exists (runflag ))
{
File. Delete (runflag );
}
}

/// <Summary>
/// Obtain or set the program running flag, which must comply with the Windows File naming rules
/// The temporary file is generated here. If you modify it to set the registry, you do not need to comply with the file naming rules.
/// </Summary>
Public static string runflag
{
Get
{
If (runflagfullname = NULL)
{
String assemblyfullname = assembly. getentryassembly (). fullname;
// Commonapplicationdata: // "C: \ Documents ents and Settings \ All Users \ Application Data"
String Path = environment. getfolderpath (environment. specialfolder. commonapplicationdata );
// "C :\\ Program Files \ common files"
// String Path = environment. getfolderpath (environment. specialfolder. commonprogramfiles );
Runflagfullname = path. Combine (path, assemblyfullname );
}
Return runflagfullname;
}
Set
{
Runflagfullname = value;
}
}
# Endregion
}
}

Program. CS file,

Using system;
Using system. Windows. forms;
Using system. diagnostics;
Using zhengzuo. csharpcode;
Namespace zhengzuo. Test. wingui
{
Static class Program
{
[Stathread]
Static void main (string [] ARGs)
{
If (ARGs. Length = 0) // No transfer parameter
{
PROCESS p = singleinstance. getrunninginstance ();
If (P! = NULL) // a copy of the application has been executed
{
Singleinstance. handlerunninginstance (P );
}
Else // start the first application
{
Runapplication ();
}
}
Else // has multiple parameters
{
Switch (ARGs [0]. tolower ())
{
Case "-API ":
If (singleinstance. handlerunninginstance () = false)
{
Runapplication ();
}
Break;
Case "-mutex ":
If (ARGs. length> = 2) // input the mutex name in the Parameter
{
If (singleinstance. createmutex (ARGs [1])
{
Runapplication ();
Singleinstance. releasemutex ();
}
Else
{
// Call singleinstance. handlerunninginstance () to display it to the foreground.
MessageBox. Show ("the program is running! ");
}
}
Else
{
If (singleinstance. createmutex ())
{
Runapplication ();
Singleinstance. releasemutex ();
}
Else
{
// Call singleinstance. handlerunninginstance () to display it to the foreground.
MessageBox. Show ("the program is running! ");
}
}
Break;
Case "-flag": // This method must be called when the program exits.
If (ARGs. length> = 2) // input the name of the running flag file in the Parameter
{
Singleinstance. runflag = ARGs [1];
}
Try
{
If (singleinstance. initrunflag ())
{
Runapplication ();
Singleinstance. disposerunflag ();
}
Else
{
// Call singleinstance. handlerunninginstance () to display it to the foreground.
MessageBox. Show ("the program is running! ");
}
}
Catch (exception ex)
{
MessageBox. Show (ex. tostring ());
}
Break;
Default:
MessageBox. Show ("application parameter setting failed. ");
Break;
}
}
}
// Start the application
Static void runapplication ()
{
Application. enablevisualstyles ();
Application. Run (New mainform ());
}
}
}

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.