Three methods for creating a single-instance application

Source: Internet
Author: User

Background
When writing windows desktop applications, we can open multiple application instances without special processing. For example, if you open multiple QQ programs on the same machine, you can also open multiple browser windows. However, some applications only run on a single instance, such as Outlook and MSN. How to implement a single-instance application? Three methods are described below.

Method 1: scan the process
This is the easiest way to think of and is easy to implement. For example, the scan process code is named mysingleinstance.exe. Www.2cto.com

Process [] processes = Process. GetProcessesByName ("MySingleInstance"); // no ". exe"
If (processes. Length> 1 ){
MessageBox. Show ("Another instance is running .");
Return;
}
A few lines of code can be used to implement the singleton application, but it is slightly unfriendly, because when trying to open the second instance, A unfriendly dialog box "Another instance is running will pop up. ", but if we remove this line of code, there is a lack of user interaction. Therefore, we can install MSN or OUTLOOK to activate a running instance.

The following code calls the windows api:

Process [] processes = Process. GetProcessesByName ("MySingleInstance ");
If (processes. Length> 1 ){
IntPtr hwnd = processes [0]. main1_whandle;
// NOTE: ensure the first intance handle selected
If (Process. GetCurrentProcess (). main1_whandle = hwnd ){
Hwnd = processes [1]. main1_whandle;
}

Long style = GetWindowLong (hwnd, GWL_STYLE );

If (style & WS_MINIMIZE) = WS_MINIMIZE ){
ShowWindow (hwnd, SW_SHOWNOACTIVATE );
}
SetForegroundWindow (hwnd );
Return;
}
The Declaration of the windows api used is as follows:

[DllImport ("user32.dll")]
Private static extern bool ShowWindow (IntPtr hWnd, uint nCmdShow );
[DllImport ("user32.dll")]
Private static extern bool SetForegroundWindow (IntPtr hwnd );
[DllImport ("user32.dll")]
Private static extern long GetWindowLong (IntPtr hwnd, int nIndex );

Private const int SW_SHOWNOACTIVATE = 4;
Const int GWL_STYLE =-16;
Const long WS_MINIMIZE = 0x20000000L;
Program1.cs near the complete code key
Method 2: Mutex
If you think the scanning process is "clumsy", you can use Mutex in a slightly professional way. If you have multi-threaded development experience, you should have used Mutex. This type of comparison can achieve thread synchronization and can be named and cross-process. Mutex constructor Signature: Mutex (bool initiallyOwned, string name, out bool createdNew). createdNew indicates that Mutex with the same name already exists. If createdNew exists, it is false, true if no. This value can be used to determine whether an application instance has been created. If createdNew is false, method 1 is required to activate the created instance window. In fact, Mutex does not reduce the complexity of creating a single instance, but is more complicated, and the created Mutex object is no longer used. It also consumes resources to create this object. This method is generally not used.

Method 3: Microsoft. VisualBasic. ApplicationServices. WindowsFormsApplicationBase
Of course, we have a simpler and more professional Method -- use WindowsFormsApplicationBase, the interface provided by Microsoft. Ms provides the Application base class and IsSingleInstance attributes. This class is located in the namespace Microsoft. VisualBasic. ApplicationServices and must be referenced by Microsoft. VisualBasic. dll. All we need to do is implement this class and set the attribute IsSingleInstance = True. Implementation Code:

Internal sealed class MySingleInstanceApplication: WindowsFormsApplicationBase {
Public MySingleInstanceApplication (){
Base. IsSingleInstance = true;
Base. EnableVisualStyles = true;
}

Protected override void OnCreateMainForm (){
This. MainForm = new Form1 ();
}
}
This class is basically the same as the Application class and looks more concise.
[STAThread]
Static void Main (string [] args ){
MySingleInstanceApplication app = new MySingleInstanceApplication ();
App. Run (args );
}
The running effect is the same as that of method 1 and method 2. The key is that the Code is more concise and object-oriented. For the complete code, see Program3.cs.

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.