Hide the system function popup window under windows

Overview

The following program is to solve the problem that the window will pop up when the system() function is called under Windows.

head File

#include <windows.h>

source code

copy code
/**
* @brief normal character to wide character
*
* @param lpcszStr ordinary character
* @param lpwszStr converted wide character
* @param dwSize buffer size to store wide characters
*
* @return
*/
BOOL MByteToWChar(LPCSTR lpcszStr, LPWSTR lpwszStr, DWORD dwSize)
{
// Get the required size of the buffer that receives the Unicode 
// string. 
DWORD dwMinSize;
dwMinSize = MultiByteToWideChar (CP_ACP, 0, lpcszStr, -1, NULL, 0);

if(dwSize < dwMinSize)
{
return FALSE;
}


// Convert headers from ASCII to Unicode.
MultiByteToWideChar (CP_ACP, 0, lpcszStr, -1, lpwszStr, dwMinSize); 
return TRUE;
}
copy code
copy code
/**
* @brief wide character to normal character
*
* @param lpcwszStr wide character
* @param lpszStr converted ordinary characters
* @param dwSize the size of the buffer to store normal characters
*
* @return
*/
BOOL WCharToMByte(LPCWSTR lpcwszStr, LPSTR lpszStr, DWORD dwSize)
{
DWORD dwMinSize;
dwMinSize = WideCharToMultiByte(CP_OEMCP,0,lpcwszStr,-1,NULL,0,NULL,FALSE);
if(dwSize < dwMinSize)
{
return FALSE;
}
WideCharToMultiByte(CP_OEMCP,0,lpcwszStr,-1,lpszStr,dwSize,NULL,FALSE);
return TRUE;
}
copy code
copy code
/**
* @brief
* The WinExec and ShellExecute functions will not wait for the command execution to complete during execution.
* It will cause the file to be executed without decompression, which does not meet our needs
* ret=WinExec(cmd,SW_HIDE);
* ShellExecute((HWND)"open", LPCWSTR(cmd), NULL, NULL,NULL,SW_HIDE);
*
* The system function call is OK, but a window will pop up
* ret = system(cmd);
*
* in the following way
*
* @param cmd The > symbol cannot appear here
*
* @return
*
*/
int nb_system (char *cmd)
{
wchar_t cmd_w[2048] = {0};
MByteToWChar(cmd, cmd_w, sizeof(cmd_w)/sizeof(cmd_w[0]));
STARTUPINFO si;
ZeroMemory(&si, sizeof(si));
si.cb = sizeof STARTUPINFO;

PROCESS_INFORMATION pi={0};
if(CreateProcess(NULL,cmd_w,NULL,NULL,TRUE,NORMAL_PRIORITY_CLASS | CREATE_NO_WINDOW,NULL,NULL,&si,&pi))
{
// Wait for the process to finish 
WaitForSingleObject(pi.hProcess ,INFINITE);


// Release resources 
CloseHandle(pi.hProcess);
CloseHandle(pi.hThread );
}
else
{
// Failure to run 
return - 1 ;
}

return 0;
}
copy code

test

intmain ()

{
   nb_system("dir");
}

 

Notice

This example uses the CreateProcess function, which does not support the > symbol, so the processing related to the > symbol in the command will not be executed

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324818540&siteId=291194637