Programmatically close Windows console application c++

349 views Asked by At

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?

2

There are 2 answers

4
David Haim On BEST ANSWER

you can hide it by

ShowWindow(GetConsoleWindow(), SW_HIDE);

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

0
user3476093 On

_gettchar() is used to stop the console from closing, thus only allowing it when you want to keep the console open will mean if you want it to close, it will:

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);
        return 0;
    }
    else
    {
         _tprintf_s(TEXT("The application has been opened the first time."));
         _gettchar();
    }
    return 0;
}