如何隐藏console窗口

FreeConsole();

在启动console后释放console,console突然闪退

#pragma comment(linker, "/subsystem:"windows" /entry:"mainCRTStartup"")

#pragma comment(linker, "/subsystem:"windows" /entry:"mainCRTStartup"")
调用上面这条C的命令,能够使链接器不去调用cmd窗口

micorosoft

#pragma comment( comment-type [ , "comment-string" ] ) // Places a comment record into an object file or executable file.

stackoverflow

1. #pragma comment // is a compiler directive which indicates Visual C++ to leave a comment in the generated object file.
 The comment can then be read by  the linker when it processes object files.
2. #pragma comment(lib, libname) //tells the linker to add the 'libname' library to the list of library dependencies, as
 if you had added it in the project properties at Linker->Input->Additional dependencies

调用外部进程

stdlib.h下面的函数

system("XXX");

这个函数即使使用了 #pragma comment 来不调用cmd窗口,但是在启动XXX命令的时候还是会启动一个外部CMD窗口来调用XXX,而FreeConsle效果不好,因此不建议使用

windows.h下面的函数

WinExce

WINBASEAPI
UINT
WINAPI
WinExec(
    _In_ LPCSTR lpCmdLine,
    _In_ UINT uCmdShow
    );
// 这个函数第二个参数就是win32里面的nCmdShow,常用的有SW_HIDE(表示不显示目的调用窗口)和SW_SHOW

使用例子

# include <Windows.h>
#pragma comment(linker, "/subsystem:\"windows\" /entry:\"mainCRTStartup\"") // 因为这个是console应用,这样可以不开启console
int main() {
	/// 这样还是会产生控制台,只是会一下子释放控制台的内存而已
	WinExec("./active_bg_run/active_bg.exe", SW_SHOW);
}

CreateProcess();

//函数原型
WINBASEAPI
BOOL
WINAPI
CreateProcessW(
    _In_opt_ LPCWSTR lpApplicationName,
    _Inout_opt_ LPWSTR lpCommandLine,
    _In_opt_ LPSECURITY_ATTRIBUTES lpProcessAttributes,
    _In_opt_ LPSECURITY_ATTRIBUTES lpThreadAttributes,
    _In_ BOOL bInheritHandles,
    _In_ DWORD dwCreationFlags,
    _In_opt_ LPVOID lpEnvironment,
    _In_opt_ LPCWSTR lpCurrentDirectory,
    _In_ LPSTARTUPINFOW lpStartupInfo,
    _Out_ LPPROCESS_INFORMATION lpProcessInformation
    );

使用列子

ShellExecute

//函数原型
SHSTDAPI_(HINSTANCE) ShellExecuteW(_In_opt_ HWND hwnd, _In_opt_ LPCWSTR lpOperation, _In_ LPCWSTR lpFile, _In_opt_ LPCWSTR lpParameters,
    _In_opt_ LPCWSTR lpDirectory, _In_ INT nShowCmd);

使用例子

CreateProcess 和 ShellExecute 可以前往 官网 查看