我的目标是在我的程序中执行外部可执行文件。首先,我使用了system()
函数,但我不想让用户看到控制台。所以,我搜索了一下,找到了CreateProcess()
函数。然而,当我尝试传递参数给它时,不知道为什么,它失败了。我从MSDN上复制了这段代码,并稍作修改:
#include <windows.h>
#include <stdio.h>
#include <tchar.h>
void _tmain( int argc, TCHAR *argv[] )
{
STARTUPINFO si;
PROCESS_INFORMATION pi;
ZeroMemory( &si, sizeof(si) );
si.cb = sizeof(si);
ZeroMemory( &pi, sizeof(pi) );
/*
if( argc != 2 )
{
printf("Usage: %s [cmdline]\n", argv[0]);
return;
}
*/
// Start the child process.
if( !CreateProcess( NULL, // No module name (use command line)
L"c:\\users\\e\\desktop\\mspaint.exe", // Command line
NULL, // Process handle not inheritable
NULL, // Thread handle not inheritable
FALSE, // Set handle inheritance to FALSE
0, // No creation flags
NULL, // Use parent's environment block
NULL, // Use parent's starting directory
&si, // Pointer to STARTUPINFO structure
&pi ) // Pointer to PROCESS_INFORMATION structure
)
{
printf( "CreateProcess failed (%d).\n", GetLastError() );
return;
}
// Wait until child process exits.
WaitForSingleObject( pi.hProcess, INFINITE );
// Close process and thread handles.
CloseHandle( pi.hProcess );
CloseHandle( pi.hThread );
}
然而,这段代码会出现访问冲突的问题。我能否在不显示控制台给用户的情况下执行 mspaint?
非常感谢。
CreateProcess
要求它的第二个参数(如果提供)是一个非const字符串。我不确定这在实践中是否会成为问题,但出于完整性考虑,我想提一下。 - reubenkernel32.dll!76da70ac() [下面的帧可能不正确和/或缺失,kernel32.dll没有加载符号] > msvcr100d.dll!_nh_malloc_dbg(unsigned int nSize, int nhFlag, int nBlockUse, const char * szFileName, int nLine) Line 302 + 0x1d bytes C++
- John Doe