/// <summary> /// 非同期処理にてタスクを開始する(前に実行された非同期タスクが存在する場合) /// タスク内容:各外部アプリケーションにファイルと引数を渡し、ファイルを出力させる /// 外部アプリケーションの出力したメッセージはイベントハンドラにて捕捉、フォームに出力させる /// </summary> /// <param name="strAppName">外部アプリケーション名(パスと拡張子を除いたファイルの名前、%~nと同義)</param> /// <param name="strInputFileName">入力ファイル名(パスと拡張子を除いたファイルの名前、%~nと同義)</param> /// <param name="strOutputFileName">出力ファイル名(パスと拡張子を除いたファイルの名前、%~nと同義)</param> /// <param name="taskBefore">この処理の前に行う非同期処理のタスク</param> /// <param name="dlgTaskAfter">外部アプリケーションの処理終了を待ってから行う処理</param> /// <returns>この非同期処理のタスクのオブジェクト</returns> private Task TaskExtAppExecute(ExternalAppSettings setting, Task taskBefore) { if (taskBefore == null) { // 前処理が設定されていない場合、空のタスクを作成する taskBefore = Task.Factory.StartNew(new Action(() => { })); } // 非同期処理1(前に起動された非同期処理を待った後に行う) Action <Task> actFirst = new Action <Task>((task) => { // テキストボックスに処理のログを表示 mainForm.InvokeUpdateLabel( (Action <string, Label>)mainForm.UpdateLabel , setting.AppName + "の処理を実行中です。" , mainForm.ProcessStatusLabel ); // 設定したコマンドライン引数を渡して外部アプリケーションを起動 Process process = MyExtApplication.ProcessStart(setting); // プロセスが終了するまで待機する処理&待機中に行う処理 process = ProcessWait(process); // プロセスが終了した後に行う処理 ProcessEnd(); }); // 非同期処理2(非同期処理1の終了を待ってから実行する) Action <Task> actNext = new Action <Task>((task) => { mainForm.InvokeUpdateLabel( (Action <string, Label>)mainForm.UpdateLabel , setting.AppName + "の処理が終了しました。" , mainForm.ProcessStatusLabel ); if (setting.AfterAction != null) { // デリゲートが入力されている場合はそのメソッドを実行する setting.AfterAction(); } }); // 複数の非同期処理の同期処理 Task taskAsync = taskBefore .ContinueWith(actFirst) .ContinueWith(actNext); // TODO // コマンドライン引数が間違っていて、アプリケーションが起動はしたが処理を開始しない場合にどうエラー判定するか // コマンドライン引数のValidation return(taskAsync); }
/// <summary> /// 外部アプリケーションを起動するためのプロセスを作成し、コマンドライン引数を渡した状態で起動する /// (アプリケーションのディレクトリを指定して起動) /// </summary> /// <param name="strAppName">アプリケーション名</param> /// <param name="strAppDir">アプリケーションの格納されているディレクトリ</param> /// <param name="strAppArg">コマンドライン引数</param> /// <returns>外部アプリケーションの標準出力</returns> public static Process ProcessStart(ExternalAppSettings setting) { // プロセスのオブジェクトを作成 Process process = new Process(); try { // 外部アプリケーションをプロセスのオブジェクトに関連付ける process.StartInfo.FileName = setting.AppRoot; // プロセスに渡す引数を設定 process.StartInfo.Arguments = setting.ArgumentString; // 標準出力を受け取る設定 process.StartInfo.RedirectStandardOutput = true; // 実行時にシェルを使うかの設定(ウインドウを隠すときはfalseにしなければならない) process.StartInfo.UseShellExecute = false; // ウインドウを隠すかどうかの設定 process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden; // 外部アプリケーションの画面を非表示(GUIがない場合) process.StartInfo.CreateNoWindow = true; // 起動失敗時にエラーダイアログを表示 process.StartInfo.ErrorDialog = true; //// 標準出力を取得するイベントハンドラ process.OutputDataReceived += MainForm.form.process_OutputDataReceived; process.Start(); process.BeginOutputReadLine(); } catch (Exception ex) { MyErrorHandling.showErrorMessage(ex.Message, ex); } return(process); }