How to check if the program is run from a console?

You can use GetConsoleWindow, GetWindowThreadProcessId and GetCurrentProcessId methods.

1) First you must retrieve the current handle of the console window using the GetConsoleWindow function.

2) Then you get the process owner of the handle of the console window.

3) Finally you compare the returned PID against the PID of your application.

Check this sample (VS C++)

#include "stdafx.h"
#include <iostream>
using namespace std;
#if       _WIN32_WINNT < 0x0500
  #undef  _WIN32_WINNT
  #define _WIN32_WINNT   0x0500
#endif
#include <windows.h>
#include "Wincon.h" 

int _tmain(int argc, _TCHAR* argv[])
{   
    HWND consoleWnd = GetConsoleWindow();
    DWORD dwProcessId;
    GetWindowThreadProcessId(consoleWnd, &dwProcessId);
    if (GetCurrentProcessId()==dwProcessId)
    {
        cout << "I have my own console, press enter to exit" << endl;
        cin.get();
    }
    else
    {
        cout << "This Console is not mine, good bye" << endl;   
    }


    return 0;
}

The typical test is:

if( isatty( STDOUT_FILENO )) {
        /* this is a terminal */
}

I needed this in C#. Here's the translation:

[DllImport("kernel32.dll")]
static extern IntPtr GetConsoleWindow();

[DllImport("kernel32.dll")]
static extern IntPtr GetCurrentProcessId();

[DllImport("user32.dll")]
static extern int GetWindowThreadProcessId(IntPtr hWnd, ref IntPtr ProcessId);

static int Main(string[] args)
{
    IntPtr hConsole = GetConsoleWindow();
    IntPtr hProcessId = IntPtr.Zero;
    GetWindowThreadProcessId(hConsole, ref hProcessId);

    if (GetCurrentProcessId().Equals(hProcessId))
    {
        Console.WriteLine("I have my own console, press any key to exit");
        Console.ReadKey();
    }
    else
        Console.WriteLine("This console is not mine, good bye");

    return 0;
}

I18N guru Michael Kaplan of Microsoft provided a series of methods on his blog that let you check a bunch of things on the console, including whether or not the console has been redirected.

They're written in C#, but porting to C or C++ would be very straightforward, as it's all done with calls to the Win32 API.


After trying quite many different api's and calls, I've found out only one working approach:

bool isConsole = isatty(fileno(stdin));

Stdout cannot be used as you can run console application and redirect output to file using >log.txt switch. Suspect it's also possible to redirect input as well, but it's quite rarely used functionality when running console applications.