4

shutdown.exe を使用して一定時間後にコンピューターをシャットダウンするプロセスを作成したいと考えています。

これが私のコードです:

ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.CreateNoWindow = false;
startInfo.UseShellExecute = false;
startInfo.WindowStyle = ProcessWindowStyle.Hidden;
startInfo.FileName = "shutdown.exe";
startInfo.Arguments = "–s –f –t " + seconds;
Process.Start(startInfo);

secondsが int ローカル変数である場合、ユーザーが決定します。

コードを実行しても何も起こりません。しかし、手動で cmd プロンプトに移動して次のように入力すると、
shutdown.exe - s -f -t 999と入力
すると、Windows によってポップアップが表示され、システムが 16 分以内にシャットダウンすることが通知されます。

複数の引数が原因だと思う理由は、進行中のシステムシャットダウンを中止する方法が機能するためです(cmdプロンプトからsystemshutdownを手動で作成した場合)。startInfo.Argumentを除いて、これはほとんど同じです。

ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.CreateNoWindow = false;
startInfo.UseShellExecute = false;
startInfo.WindowStyle = ProcessWindowStyle.Hidden;
startInfo.FileName = "shutdown.exe";
startInfo.Arguments = "-a";
Process.Start(startInfo);
4

1 に答える 1

8

shutdown.exe の使用法メッセージを簡単に調べると、ダッシュ ('-') ではなくスラッシュ ('/') の後にオプション引数が必要であることがわかります。

ラインの交換:

        startInfo.Arguments = "–s –f –t " + seconds;

と:

        startInfo.Arguments = "/s /f /t " + seconds;

C# Express 2010 を使用して、私のボックスで動作する結果が得られます。

また、実行後に何が起こったかを知ることができるように、開始されたプロセスから標準エラーと標準アウトをリダイレクトして、プログラムが読み取るようにすることもできます。これを行うには、Process オブジェクトを保存し、基になるプロセスが終了するのを待って、すべてがうまくいったかどうかを確認できるようにします。

        startInfo.RedirectStandardOutput = true;
        startInfo.RedirectStandardError = true;

        Process p = Process.Start(startInfo);
        string outstring = p.StandardOutput.ReadToEnd();
        string errstring = p.StandardError.ReadToEnd();
        p.WaitForExit();

残念ながら、コマンド ライン バージョンではオプションの「ダッシュ」プレフィックスが受け入れられ、C# 実行バージョンでは受け入れられない理由を説明できません。ただし、うまくいけば、あなたが求めているのは実用的な解決策です。

以下のコードの完全なリスト:

        int seconds = 100;
        ProcessStartInfo startInfo = new ProcessStartInfo();
        startInfo.CreateNoWindow = false;
        startInfo.UseShellExecute = false;
        startInfo.WindowStyle = ProcessWindowStyle.Hidden;
        startInfo.FileName = "shutdown.exe";
        startInfo.Arguments = "/s /f /t " + seconds;
        startInfo.RedirectStandardOutput = true;
        startInfo.RedirectStandardError = true;
        Process p = Process.Start(startInfo);
        string outstring = p.StandardOutput.ReadToEnd();
        string errstring = p.StandardError.ReadToEnd();
        p.WaitForExit();
于 2012-01-18T18:31:22.833 に答える