Prevent a duplicate run of a Windows program that does not have a form

Source: Internet
Author: User
Tags mutex

With mutexes (mutexes), a mutex is inherently multithreaded, preventing multiple threads from accessing the same resource and causing a conflict. You can create a mutex object with CreateMutex, which is essentially a kernel object.

Add the following code to the startup portion of any WIN32 program (including GDI and console) (the console program's main function, the MFC program's CWinApp derived class's InitInstance member function, the RAWSDK program's WinMain function):

hMutex=CreateMutex(
NULL,//nosecurityattributes
FALSE,//initiallynotowned
"RunOnlyOneInstance");//命名Mutex是全局对象
//在所有的process都可以访问到
if(hMutex==NULL||ERROR_ALREADY_EXISTS==::GetLastError())
{
//程序第二次或以后运行时,会得到Mutex已经创建的错误
returnFALSE;
}

Hey, is not not findwindow elegant and simple much?

In addition, what if you want to qualify a program to run N instances at the same time?

Tips: Signal Volume (semaphore).

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.