パラメータを使用して外部プログラムを呼び出す方法は?

CreateProcess()、System() などを呼び出すときは、ファイル名や完全修飾パスにスペースが含まれている場合に備えて、ファイル名の文字列 (コマンド プログラムのファイル名を含む) を二重引用符で囲んでください。ファイル名パスの一部は、コマンド インタープリターによって個別の引数として解析されます。

system("\"d:some path\\program.exe\" \"d:\\other path\\file name.ext\"");

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);

(または SW_SHOW_NORMAL コマンド ウィンドウを表示したい場合)。

Windows はシステム PATH で command.com または cmd.exe を検出する必要があるため、完全修飾する必要はありませんが、確実にしたい場合は、CSIDL_SYSTEM を使用して完全修飾ファイル名を作成できます。 (単に C:\Windows\system32\cmd.exe を使用しないでください)。


C++ の例:

char temp[512];
sprintf(temp, "command -%s -%s", parameter1, parameter2);
system((char *)temp);

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
        }
    }

Windows API で CreateProcess 関数を探していると思います。実際には関連する一連の呼び出しがありますが、これで始められます。とても簡単です。