Search code examples
winapivb6exeshellexecute

Can one detect how .exe was launched?


I want to be able to detect whether a given exe was shellex'd programmatically or if it was entered and executed interactively in, say, CMD.EXE.

Is there anything about the way an exe is launched that indicates the mechanism that was used to launch it?

Context: Windows XP, Visual Studio 6 languages.


Solution

  • There might be an easier way, but the only way I can think of is to check the parent process name, which involves a few steps:

    1. Get the ID of the parent process.
    2. Get the handle of the process, using the ID.
    3. Use GetModuleFileNameEx with the handle found (and NULL as the module) to get the executable's name.
    4. Check if the executable's name is cmd.exe or whatever.

    Bear in mind that the parent process might already be gone when (or while) you do this check.

    Edit:

    If your program is a console application, you can also check the console it's running in. If it was run from cmd, it will usually use the same console. So, you can use GetConsoleTitle, for instance, and see if it's "Command Prompt". This might not work on localized or different versions of Windows, but it's easy if you have limitated cases. You can also use GetConsoleWindow and GetWindowThreadProcessId instead of steps 1 and 2.