2

いくつかの作業を行うスレッドを作成し、shutdown.exe を実行して PC をシャットダウンします。

Worker work = new Worker();
Thread thread = new Thread(new ThreadStart(work.DoWork));
thread.Start();

およびメソッド DoWork()

public void DoWork()
{
        /* Do some thing */

        // This will shutdown the PC
        ProcessStartInfo startInfo = new ProcessStartInfo(Environment.GetFolderPath(System.Environment.SpecialFolder.System) + @"\shutdown.exe", "-s -t 5");
        Process.Start(startInfo);
}

メイン スレッドでメソッド work.DoWork() を呼び出すと、PC がシャットダウンします。しかし、thread.Start() を使用してスレッドに入れると、PC はシャットダウンしません。

編集:間違いを見つけました。常にfalseを返すチェックボックスを読み取るためのスレッドセーフな呼び出しメソッドを作成します

    delegate bool GetcbShutdownCheckedValueCallback();

    public bool GetcbShutdownCheckedValue()
    {
        // InvokeRequired required compares the thread ID of the
        // calling thread to the thread ID of the creating thread.
        // If these threads are different, it returns true.
        if (this.lblCraftRemain.InvokeRequired)
        {
            GetcbShutdownCheckedValueCallback d = new GetcbShutdownCheckedValueCallback(GetcbShutdownCheckedValue);
            this.Invoke(d);
        }
        else
        {
            return cbShutdown.Checked;
        }
        return false;
    }

メソッドを呼び出して、チェックボックスがオンになっているかどうかを確認してからシャットダウンします。したがって、実際にはコードは実行されません。

4

1 に答える 1

0

コンピュータをシャットダウンしたい場合は、プログラムExitWindowsを実行するよりも Win32 の関数を呼び出す方がよいでしょうshutdown.exe

ここに MSDN ドキュメントがあります: http://msdn.microsoft.com/en-us/library/windows/desktop/aa376867%28v=vs.85%29.aspx

C# P/Invoke 署名はこちら: http://www.pinvoke.net/default.aspx/user32.exitwindowsex

于 2012-07-30T03:43:44.517 に答える