To meet the needs of a projectProgramOnly one instance is running. I searched the internet for a long time and finally saw a reply on csdn. Get inspiration and complete this function.
It is mainly implemented using mutex objects.CodeAs follows:
Static Class Program
{
[Dllimport ( " Coredll. dll " , Setlasterror = True )]
Private Static Extern Intptr createmutex (security_attributes lpmutexattributes, Bool Binitialowner, String Lpname );
[Dllimport ("Coredll. dll", Setlasterror= True)]
Private Static Extern IntReleasemutex (intptr hmutex );
[Structlayout (layoutkind. Sequential)]
Public Class Security_attributes
{
Public Int Nlength;
Public Int Lpsecuritydescriptor;
Public Int Binherithandle;
}
Const IntError_already_exists= 0183;
/// <Summary>
/// The main entry point of the application.
/// </Summary>
[Mtathread]
Static Void Main ()
{
Intptr hmutex = Createmutex ( Null , False , " Standardworkman " );
If (Marshal. getlastwin32error () ! = Error_already_exists)
{
Application. Run ( New Formworklist ());
}
Else
{
MessageBox. Show ( " A program has been started. Do not open it again " , " System prompt " ,
Messageboxbuttons. okcancel, messageboxicon. Asterisk, messageboxdefaultbutton. button1 );
Releasemutex (hmutex );
Application. Exit ();
}
}
}
The above code is completely normal. My problem is that most of them wrote it very early. The problem is as follows:
[Dllimport ( " Coredll. dll " , Setlasterror = True )]
Private Static Extern Int Getlasterror ();
.
If (Getlasterror () ! = Error_already_exists)
{
Application. Run (NewFormworklist ());
}
I use getlasterror () in the platform call, and the result is always desired. No matter how many instances are opened, the value of getlasterror () is always 6 (invalid_handle_value )???? I am puzzled. Let us explain it. Thank you.