Search code examples
c++windowsmutexhandle

Programmatically close Windows console application c++


I need my windows console application to be run only in one instance (i.e. Only one instance of the application can be run at a time). Here's what I have:

int _tmain(int argc, _TCHAR* argv[])
{
    PCTSTR Name = TEXT("AnyName");
    HANDLE h = CreateMutex(NULL, FALSE, Name);

    if (GetLastError() == ERROR_ALREADY_EXISTS)
    {
        _tprintf_s(TEXT("This application is already opened."));
        CloseHandle(h);
        // Close the console somehow
        return 0;
    }
    else _tprintf_s(TEXT("The application has been opened the first time."));

    _gettchar();
    return 0;
}

How can I programmatically close the console window if the same program is already initialized?


Solution

  • you can hide it by

    ShowWindow(GetConsoleWindow(), SW_HIDE);
    

    Although I really think you should quit the program instead just closing the console.