4

The program I am writing is a simple console application that gets params, computes, and then returns data.

I am asking this because I am trying to implement a smart "press enter to exit" message that would run only if a console program is called by clicking on its icon in explorer. Without it, the result is that program only flashes for a split of second, but if a program is run from a context of already opened console then the same thing becomes an annoyance. Similar thing arises when program is run inside bat or cmd file, then pausing at the end is also unwelcome since bat files have 'pause' command that is supposed to do it.


So, we have 2 modes:

  • program says "press enter to exit" when is started by:
    • direct clicking in explorer
    • clicking on a shortcut
  • Simply exit when:
    • its name is typed in console
    • it is run from a bat/cmd file
    • it is run from another console application
4
  • 1
    I'd alternatively add an extra argument to the program to either make it wait for input or stop it from waiting, or even have a timer so that the user has time to read the output but the program still doesn't wait infinitely.
    – AusCBloke
    Commented Dec 22, 2011 at 22:48
  • 2
    hmm, as I think of it the correct way would be to get a list of processes that are using console window, and if it equals one it means that we have case 1... I'm very new to anything C so, really I don't know.
    – rsk82
    Commented Dec 22, 2011 at 22:55
  • There's no way of detecting this, other than by passing command line parameters from a shortcut (.lnk) file or batch file. If you don't get the parameter, it was started by directly running it or double-clicking it in Explorer. Windows doesn't distinguish the different ways your process is started; it's just started.
    – Ken White
    Commented Dec 22, 2011 at 22:57
  • Press Ctrl+F5. F5 was designed for you to set a breakpoint on the code you care about debugging. Commented Dec 22, 2011 at 23:03

5 Answers 5

6

Using Windows APIs:

You can use the GetConsoleProcessList API function (available on Windows XP/2003 and higher only). It returns a list of processes that are attached to the current console. When your program is launched in the "no console" mode, your program is the only process attached to the current console. When your program is launched from another process which already has a console, there will be more than one process attached to the current console.

In this case, we don't care about the list of process IDs returned by the function, we only care about the count that is returned.

Example program (I used Visual C++ with a Console Application template):

#include "stdafx.h"
#include <iostream>
#include <Windows.h>

using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
    DWORD procIDs[2];
    DWORD maxCount = 2;
    DWORD result = GetConsoleProcessList((LPDWORD)procIDs, maxCount);
    cout << "Number of processes listed: " << result << endl;
    if (result == 1)
    {
        system("pause");
    }
    return 0;
}

We only need to list up to 2 processes, because we only care whether there is 1 or more than 1.


Using Windows APIs present in Windows 2000:

GetConsoleWindow returns the window handle of the console associated with the current process (if any). GetWindowThreadProcessId can tell you which process created a window. And finally, GetCurrentProcessId tells you the id of current process. You can make some useful deductions based on this information:

#include "stdafx.h"
#include <iostream>
#include <Windows.h>

using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
    HWND consoleWindow = GetConsoleWindow();
    if (consoleWindow != NULL)
    {
        DWORD windowCreatorProcessId;
        GetWindowThreadProcessId(consoleWindow, &windowCreatorProcessId);
        if (windowCreatorProcessId == GetCurrentProcessId())
        {
            cout << "Console window was created by this process." << endl;
            system("pause");
        }
        else
            cout << "Console window was not created by this process." << endl;
    }
    else
        cout << "No console window is associated with this process." << endl;
    return 0;
}

This technique seems slightly less precise than the first one, but I think in practice it should perform equally well.

3
  • this is nice answer. But has a one annoying issue - function GetConsoleProcessList can't be run on windows 2000
    – rsk82
    Commented Dec 23, 2011 at 0:03
  • @rsk82 Yes, sadly GetConsoleProcessList was not added until XP/2003. However, I found a solution which uses only Windows 2000 API calls and should work as well as the GetConsoleProcessList method. I updated my answer.
    – tcovo
    Commented Dec 23, 2011 at 5:54
  • It turns out both of these methods were offered (in some form) in answer to this question: stackoverflow.com/questions/1482604/… There, the windows API calls are made from Delphi, but the goal is essentially the same as in this question.
    – tcovo
    Commented Dec 23, 2011 at 7:34
2

The simplest solution I can think of is require the first parameter to be a flag whether or not the program should pause at the end. If the parameter is not there, i.e. it was started via explorer and the user did not have the ability to pass it in, then it should pause.

//Pseudo-code!!

int main(int argc, char** argv) {
    //...
    if(argv[1] == SHOULD_PAUSE) system("pause");
    return 0;
}
0

There's a simple way to do this, and of course a more complicated way. The more complicated way may be more fun in the end, but probably more trouble than it's worth.

For the simple way, add a command line argument to the program, --pause-on-exit or something similar. Pass the extra arg whan calling it from a batch-file or the launcher icon. You could of course rather check for an environment variable for a similar effect.

For a more complicated (and automatic) way, you could probably try to find out who is the parent process of your application. You may have to go further up the chain than your immediate parent, and it may not work in all cases. I'd go for the command line argument.

0

Elaborating on my comment, rather than trying to tell how the program was executed (which I don't know is even possible, I'd assume there's no difference/distinction at all), I would implement a similar functionality in either one of two ways:

  • Add an extra argument to the program that will either make it "pause" at the end before terminating or not. ie. You could have something like -w to make it wait, or -W to make it not wait, and default with not waiting (or vice versa). You can add arguments through shortcuts.

  • Add a timer at the end of the program so that you wait for a few seconds, long enough for the user to read the input, so that the program doesn't wait infinitely when used in a batch.

0

Visual Studio introduces a wrinkle to @tcovo's otherwise valid answer when you are debugging. In this situation, it creates a second process and attaches it to the same console as the process you're running in:

Console debug snippet showing extra process

So, it's necessary to detect the debugger using the Windows API function IsDebuggerPresent in order to get a definitive answer:

#include <iostream>
#include <Windows.h>
#include "debugapi.h"

int main()
{
    DWORD pl[2];
    auto np = GetConsoleProcessList(pl, 2);
    std::cout << np << " processes\n";
    bool shared;
    if (IsDebuggerPresent())
        shared = np > 2;
    else
        shared = np > 1;
    std::cout << "Shared: ";
    std::boolalpha(std::cout);
    std::cout << shared << "\n";
    std::cin.ignore(1);
    return 0;
}

This only matters if you're using the local debugger; when run in a remote debugger there is still only one process attached.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.