1/*** // <summary>
/// Start from here
/// </Summary>
[STAThread]
Static void Main ()
{
Process instance = RunningInstance ();
If (instance = null)
{
// No instance is running
WeatherApp appInstance = new WeatherApp ();
AppInstance. StartMainGui ();
}
Else
{
// An instance is running.
HandleRunningInstance (instance );
}
}
Make sure there is only one instance # region make sure there is only one instance
Public static Process RunningInstance ()
{
Process current = Process. GetCurrentProcess ();
Process [] processes = Process. GetProcessesByName (current. ProcessName );
// Traverse the process list with the same name as the current process
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;
}
}
}
Return null;
}
Private static void HandleRunningInstance (Process instance)
{
MessageBox. Show ("this application system is already running! "," Message ", MessageBoxButtons. OK, MessageBoxIcon. Information );
ShowWindowAsync (instance. main1_whandle, 1); // call the api function. The window is displayed normally.
SetForegroundWindow (instance. main1_whandle); // place the window at the front end.
}
[DllImport ("User32.dll")]
Private static extern bool ShowWindowAsync (System. IntPtr hWnd, int cmdShow );
[DllImport ("User32.dll")]
Private static extern bool SetForegroundWindow (System. IntPtr hWnd );
# Endregion
2. [STAThread]
Static void Main (string [] args)
{
Bool isFirst;
System. Threading. Mutex mutex = new System. Threading. Mutex (true, "WindowAppTest", out isFirst );
// Here, myApp is the program identifier. We recommend that you replace it with the physical path of your program. In this way, if this flag is in one operating system, it will not conflict with other programs.
If (! IsFirst)
{
MessageBox. Show ("Exist ");
Environment. Exit (1); // The instance already exists. Exit the program
}
Else
{
Application. Run (new Form1 ());
}
}