Wil*_*ill 28 c c++ winapi external-application
我想在我的代码中调用一个windows程序,并在代码本身内确定参数.
我不打算调用外部函数或方法,而是调用WinXP环境中的实际.exe或批处理/脚本文件.
C或C++将是首选语言,但如果使用任何其他语言更容易完成,请告诉我(ASM,C#,Python等).
Rog*_*son 28
当您调用CreateProcess(),System()等时,请确保您引用文件名字符串(包括命令程序文件名),以防您的文件名和/或完全限定的路径有空格,否则部分文件名路径的名称将由命令解释器解析为单独的参数.
system("\"d:some path\\program.exe\" \"d:\\other path\\file name.ext\"");
Run Code Online (Sandbox Code Playgroud)
对于Windows,建议使用CreateProcess().它设置较为混乱,但您可以更好地控制流程的启动方式(如Greg Hewgill所述).对于快速和脏,您也可以使用WinExec().(system()可移植到UNIX).
启动批处理文件时,您可能需要使用cmd.exe(或command.com)启动.
WinExec("cmd \"d:some path\\program.bat\" \"d:\\other path\\file name.ext\"",SW_SHOW_MINIMIZED);
Run Code Online (Sandbox Code Playgroud)
(或者SW_SHOW_NORMAL如果您希望显示命令窗口).
Windows应该在系统PATH中找到command.com或cmd.exe,因此不需要完全限定,但如果你想确定你可以使用CSIDL_SYSTEM(不要只使用C:\ Windows)来编写完全限定的文件名\ SYSTEM32\CMD.EXE).
小智 11
C++示例:
char temp[512];
sprintf(temp, "command -%s -%s", parameter1, parameter2);
system((char *)temp);
Run Code Online (Sandbox Code Playgroud)
C#示例:
private static void RunCommandExample()
{
// Don't forget using System.Diagnostics
Process myProcess = new Process();
try
{
myProcess.StartInfo.FileName = "executabletorun.exe";
//Do not receive an event when the process exits.
myProcess.EnableRaisingEvents = false;
// Parameters
myProcess.StartInfo.Arguments = "/user testuser /otherparam ok";
// Modify the following to hide / show the window
myProcess.StartInfo.CreateNoWindow = false;
myProcess.StartInfo.UseShellExecute = true;
myProcess.StartInfo.WindowStyle = ProcessWindowStyle.Maximized;
myProcess.Start();
}
catch (Exception e)
{
// Handle error here
}
}
Run Code Online (Sandbox Code Playgroud)
最简单的方法之一是使用system()运行时库函数.它需要一个字符串作为参数(比CreateProcess!更少的参数)并执行它,就好像它是在命令行上键入的一样.system()还会在返回之前自动等待进程完成.
还有一些限制:
运行时库还提供了一个家庭exec*的功能(execl,execlp,execle,execv,execvp,更多或更少),它们从Unix遗产衍生,并提供对过程的控制.
在最低级别,在Win32上,所有进程都由该CreateProcess函数启动,这为您提供了最大的灵活性.