控制台程序不显示dos窗口的方法

在实际项目中,为了实现某些功能,但是不希望给用户显示windows窗口或者dos窗口时,以下是比较常用的两种方式实现窗口隐藏:

方法1

在头文件下加上一句预处理命令:

#pragma comment( linker, "/subsystem:\"windows\" /entry:\"mainCRTStartup\"" ) // 设置入口地址

这样编译出来的exe就无dos窗口了

完整程序如下:

#include<windows.h>
#pragma comment( linker, "/subsystem:\"windows\" /entry:\"mainCRTStartup\"" ) // 设置入口地址
int main()
{
    
    
    MessageBox(NULL,"Hello","Notice",NULL);
    return 0;
}

方法2

使用vb实现程序隐藏:

set objShell=wscript.createObject("wscript.shell")  
iReturn=objShell.Run("你的程序.exe", 0, FALSE)  

'Run()
'第一个参数是你要执行的程序的路径,亦可传参
'第二个参数是窗口的形式,0后台运行;1正常运行;2最小化;3最大化;缺省的话表示正常运行
'第三个参数是表示这个脚本是等待还是继续执行,如果设为了True,脚本就会等待调用的程序退出后再向后执行。

方法3

使用ShellExecuteEx API函数,示例代码如下:

    SHELLEXECUTEINFO ShellInfo;
    memset(&ShellInfo, 0, sizeof(ShellInfo));

    ShellInfo.cbSize = sizeof(ShellInfo);
    ShellInfo.hwnd = NULL;
    ShellInfo.lpVerb = _T("open");
    ShellInfo.lpFile = szFilePath; // 此处写执行文件的绝对路径
    ShellInfo.nShow = SW_SHOWNORMAL;
    ShellInfo.fMask = SEE_MASK_NOCLOSEPROCESS;//无控制台
    BOOL bResult = ShellExecuteEx(&ShellInfo);

或者

DWORD ShellRun(CString csExe, CString csParam,DWORD nShow)  
{
    
      
	SHELLEXECUTEINFO ShExecInfo;  
	ShExecInfo.cbSize = sizeof(SHELLEXECUTEINFO);  
	ShExecInfo.fMask = SEE_MASK_NOCLOSEPROCESS ;  
	ShExecInfo.hwnd = NULL;  
	ShExecInfo.lpVerb = NULL;  
	ShExecInfo.lpFile = csExe; 
	ShExecInfo.lpParameters = csParam;   
	ShExecInfo.lpDirectory = NULL;  
	ShExecInfo.nShow = nShow;  
	ShExecInfo.hInstApp = NULL;   
	BOOL ret = ShellExecuteEx(&ShExecInfo);  
	WaitForSingleObject(ShExecInfo.hProcess, INFINITE);  
	DWORD dwCode=0;  
	GetExitCodeProcess(ShExecInfo.hProcess, &dwCode);  
	CloseHandle(ShExecInfo.hProcess);  
	return dwCode;  
}  

另外ShellExecuteEx执行cmd命令的时候, 命令行参数要加入/c 来让命令行执行完成后关闭自身。否则命令行进程会一直存在, WaitForSingleObject会一直等待。

比如: ShellRun(L"cmd.exe", L"/c sc start UlogReport",SW_HIDE); 启动一个服务。

文章来源:

https://blog.csdn.net/believe_s/article/details/82389795

猜你喜欢

转载自blog.csdn.net/xiao3404/article/details/107115612
今日推荐