プログラム学習室
コマンドの実行
■ShellExecute()
#include <windows>
int main(int argc, char *argv[])
{
// 秀丸を起動する
ShellExecute(NULL, "open", "C:\\Program Files\\Hidemaru\\Hidemaru.exe", NULL, NULL, SW_SHOW);
// 秀丸を起動してD:\TEST\Sample\ReadMe.txtを開く
ShellExecute(NULL, "open", "C:\\Program Files\\Hidemaru\\Hidemaru.exe",
"D:\\TEST\\Sample\\ReadMe.txt", NULL, SW_SHOW);
// http://www11.plala.or.jp/studyhall/をブラウザで開く
ShellExecute(NULL, "open", "http://www11.plala.or.jp/studyhall/", NULL, NULL, SW_SHOW);
return 0;
}
Windows APIのShellExecute()は実行したコマンドが終了しなくとも次の行に進んでしまう。
上の例だと次々に秀丸二つとブラウザが一つ開いてしまう。
■CreateProcess()
CreateProcess()を使うと起動したプログラムが終了するまで次の処理を待つことができる。
(MSDNのサンプルコードを元に改造)
#include <windows>
#include <iostream>
using namespace std;
int main(int argc, char *argv[])
{
int iRtn = 0;
STARTUPINFO si;
PROCESS_INFORMATION pi;
ZeroMemory( &si, sizeof(si) );
si.cb = sizeof(si);
ZeroMemory( &pi, sizeof(pi) );
cout << "秀丸を起動します\n";
// 秀丸を起動する
if( !CreateProcess( NULL, // No module name (use command line).
"C:\\Program Files\\Hidemaru\\Hidemaru.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.
)
{
cout << "CreateProcess failed.";
iRtn = -1;
}
// Wait until child process exits.
WaitForSingleObject( pi.hProcess, INFINITE );
// Close process and thread handles.
CloseHandle( pi.hProcess );
CloseHandle( pi.hThread );
cout << "秀丸を終了しました\n";
return iRtn;
}
■system()
Cの標準関数のsystem()は上のCreateProcess()の例と同じく、プログラムが終了するまで次の処理を待つ。
#include <iostream>
#include <cstdlib>
using namespace std;
int main(int argc, char *argv[])
{
cout << "秀丸を起動します\n";
// 秀丸を実行する
system("\"C:\\Program Files\\Hidemaru\\Hidemaru.exe\"");
// ロングファイル名なのでダブルクォーテーションでくくる
cout << "秀丸を終了しました\n";
return 0;
}
Last Update 2008-03-09