C # How to make an application run only one instance

Source: Internet
Author: User

Using System;
Using System. Runtime. InteropServices;
Using System. Windows. Forms;
Using System. Diagnostics;
Using System. Reflection;

Public class OneInstnace
{
[STAThread]
Public static void Main ()
{
// Obtain the running routine
Process instance = RunningInstance ();
If (instance = null)
{
// If there are no other routines, create a new form
Application. Run (new Form ());
}
Else
{
// Process the detected routine
HandleRunningInstance (instance );
}
}
Public static Process RunningInstance ()
{
Process current = Process. GetCurrentProcess ();
Process [] processes = Process. GetProcessesByName (current. ProcessName );

// Traverse a routine with the same name running
Foreach (Process process in processes)
{
// Ignore existing routines
If (process. Id! = Current. Id)
{
// Ensure that the routine runs from the EXE file
If (Assembly. GetExecutingAssembly (). Location. Replace ("/", "\") = current. MainModule. FileName)
{
// Return another routine instance
Return process;
}
}
}

// If no other routine exists, Null is returned.
Return null;
}

Public static void 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
SetForegroundWindow (instance. main1_whandle );
}

[DllImport ("User32.dll")]
Private static extern bool ShowWindowAsync (IntPtr hWnd, intcmdShow );

[DllImport ("User32.dll")]
Private static extern bool SetForegroundWindow (IntPtr hWnd );
Private const int WS_SHOWNORMAL = 1;
}

Related Article

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.