How to make an application run only one instance

Source: Internet
Author: User
Tags mutex

For an application to run only one instance, a simple method is to use mutexes in the application class, which can be generated by the GUIDGEN.EXE program under VC. GUIDGEN.EXE is located in the VC installation directory Commontools directory

Instance

1: Create a new project EX1 based on the dialog box, with the default setting

2: Create a global flag with GUIDGEN.EXE, #define One "generated global flag"

The following statements are generated in this example: #define ONE "0xbe8e2ce1, 0xdab6, 0x11d6, 0xad, 0xd0, 0x0, 0xe0, 0x4c, 0x53, 0xf6, 0xe6"

3: In the Application Class Cex1app::initinstance (), create a mutex with the CreateMutex function, and then call the function GetLastError ()

If the result is equal to error_already_exists the description already has an instance running at this time returns False.bool Cex1app::initinstance () {Handle=::createmutex null,false, one);//handle is a global variable of the declared handle type

if (GetLastError () ==error_already_exists)

{

AfxMessageBox ("The application is already running");

return FALSE;

}

}

4: In Cex1app::exitinstance (), remove this mutex int cex1app::exitinstance () {

CloseHandle (handle);

return CWinApp::ExitInstance ();

}

This article supporting source code

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.