Make windows applications have only one instance

Source: Internet
Author: User
Using system;
Using system. diagnostics;
Using system. Windows. forms;
Using system. reflection;
Using system. runtime. interopservices;

Using zhzuo. wingui;

Namespace zhzuo
{
/** // <Summary>
/// Summary of appstart.
/// </Summary>
Public class applicationstart
{
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 );

/** // <Summary>
/// Main entry point of the application.
/// </Summary>
[STAThread]
Static void Main ()
{
Process instance = GetRunningInstance ();
If (instance = null)
{
// Initialize the program Configuration
// ApplicationSettings. Initialize ();
Application. Run (new MainForm ());
}
Else
{
HandleRunningInstance (instance );
}
}
/** // <Summary>
/// Obtain the application instance. If no other routine exists, Null is returned.
/// </Summary>
/// <Returns> </returns>
Public static Process GetRunningInstance ()
{
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;
}
Return null;
}
/** // <Summary>
/// Obtain the window handle
/// </Summary>
/// <Param name = "instance"> </param>
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 );
}
}
}


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.