简体   繁体   中英

Run C++ unmanaged console app (NOT a batch file) without a window

In order to avoid tangling with interop services (beyond my understanding) I use

spawnl(P_DETACH, MyPath, "MyProg.exe", 0);

to spawn a VS unmanaged C++ command line project. (It controls an astro-camera via the manufacturer's DLL).

I don't need and don't want a window (I talk to myprog.exe using named pipes from my main GUI program).

Suppressing the window from a GUI is trivial, but in order to avoid tangling with marshalling issues (beyond my comprehension) myprog.exe must be an unmanaged native C++ command line project, not a CLI project.

There is a huge literature on suppressing the window from a batch file or from python, and closing a window in a windows project is trivial, but that is all irrelevant here.

I spawn myprog.exe detached, but that is irrelevant. Closing the console handle executes ok but does not close the window.

Any thoughts on how to either never open the black onscreen DOS box, or how to close it without closing myprog.exe?

Try something like this:

#define WIN32_LEAN_AND_MEAN
#include <windows.h>

#include <stdio.h>

void system_error(char *name) {
// Retrieve, format, and print out a message from the last errror.
// The `name' that's passed should be in the form of a present tense
// noun (phrase) such as "opening file".
//
    char *ptr = NULL;
    FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER |
        FORMAT_MESSAGE_FROM_SYSTEM,
        0, GetLastError(), 0, (char *)&ptr, 1024, NULL);

    printf("\nError %s: %s\n", name, ptr);
    LocalFree(ptr);
}

PROCESS_INFORMATION p;

BOOL WINAPI die(DWORD reason) {
    TerminateProcess(p.hProcess, 1);
    return TRUE;
}

int main(int argc, char **argv) {

    STARTUPINFO s;

    memset(&s, 0, sizeof s);
    s.cb = sizeof(s);

    if (!CreateProcess(argv[1], argv[2], NULL, NULL, TRUE,
        DETACHED_PROCESS, NULL, NULL, &s, &p))
    {
        system_error("Spawning program");
        return 1;
    }

    SetConsoleCtrlHandler(die, TRUE);

    WaitForSingleObject(p.hProcess, INFINITE);
    return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM