home · archive · links · projects

windows_launcher.c

Launch an executable without cmd window in Windows

// Build in MinGW64: gcc -static -mwindow launcher.c -o launcher.exe
#include <stdbool.h>
#include <stdio.h>
#include <Processthreadsapi.h>
#include <Windows.h>

void ErrorExit(LPTSTR lpszFunction)
{
    // Retrieve the system error message for the last-error code

    LPVOID lpMsgBuf;
    DWORD dw = GetLastError();

    FormatMessage(
        FORMAT_MESSAGE_ALLOCATE_BUFFER |
        FORMAT_MESSAGE_FROM_SYSTEM |
        FORMAT_MESSAGE_IGNORE_INSERTS,
        NULL,
        dw,
        MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
        (LPTSTR) &lpMsgBuf,
        0, NULL );

    // Display the error message and exit the process

    fprintf(stderr, "%s", lpMsgBuf);
    LocalFree(lpMsgBuf);
    ExitProcess(dw);
}

char cmdbuf[4096];

int main() {
    PROCESS_INFORMATION pi = {0};
    STARTUPINFO si = {0};
    si.cb = sizeof(si);

    GetCurrentDirectory(4096, cmdbuf);
    strcat(cmdbuf, "\\sh.exe startup.sh");
    bool ret;
    ret = CreateProcess(NULL, cmdbuf, NULL, NULL, TRUE, 
                         CREATE_NO_WINDOW, NULL, NULL, &si, &pi);
    if (!ret) {
        ErrorExit("createProcess");
    }
    WaitForSingleObject(pi.hProcess, INFINITE);
    CloseHandle(pi.hProcess);
    CloseHandle(pi.hThread);
    return 0;
}

© Licensed under CC BY-NC-SA 4.0 if not specified otherwise.
Email: dzshy [at] outlook [dot] com