简体   繁体   中英

How to hide console window for nodejs (compiled with nexe)

Im making a program with node and compiling it with nexe, i have no clue how to make the console window hide though, by hide i mean it starts as a background process, directly from running the executable.

There are many methods that depend on ffi (foreign function interface) which requires python and visual studios, and in my opinion is best avoided.

One method I found to hide the console window depends on having powerscript installed (and likely a high enough version).

function hideSelf() {

    let powershellScript = `
    Add-Type -Name Window -Namespace Console -MemberDefinition '
    [DllImport("Kernel32.dll")]
    public static extern IntPtr GetConsoleWindow();

    [DllImport("user32.dll")]
    public static extern bool ShowWindow(IntPtr hWnd, Int32 nCmdShow);
    '

    $consolePtr = [Console.Window]::GetConsoleWindow()
    #0 hide
    [Console.Window]::ShowWindow($consolePtr, 0)
    `;

    let workingDir = process.cwd();
    let tempfile = `${workingDir}\\temp.ps1`;
    fs.writeFileSync(tempfile, powershellScript);

    //a little convoluted to get around powershell script execution policy (might be disabled)
    require('child_process').execSync(`type .\\temp.ps1 | powershell.exe -noprofile -`, {stdio: 'inherit'});
    fs.unlinkSync(tempfile); //delete temp file
}

If you don't have powershell, I also tried another method where I created an c++ executable with the following code:

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

using namespace std;

void HideConsole()
{
    ::ShowWindow(::GetConsoleWindow(), SW_HIDE);
}

int main(int argc, char *argv[])
{
    HideConsole();
    return 0;
}

This can be compiled with MINGW to hide.exe and then invoked in node.js with require('child_process').execSync('hide.exe', {stdio: 'inherit'}); . Note that it is necessary that the executable inherits the same console window as node.js so it will hide node.js's console.

In order to show the window again, you can pass different constants to the ShowWindow command.

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