當使用者開啟程式後,
在程式未結束前做 shutdown 時 windows 不會馬上關機,
會跳出一個詢問視窗,
按下詢問視窗的 Yes 後 windows 才會繼續關機程序。
開啟 visual studio WPF App(.NET Framework) 專案
開啟 App.xml 加入以下內容:
<Application x:Class="XXX.App"
...
SessionEnding="App_SessionEnding"
>
開啟 App.xml.cs 加入以下內容:
void App_SessionEnding(object sender, SessionEndingCancelEventArgs e)
{
// Ask the user if they want to allow the session to end
string msg = string.Format("{0}. End session?", e.ReasonSessionEnding);
MessageBoxResult result = MessageBox.Show(msg, "Session Ending", MessageBoxButton.YesNo);
// End session, if specified
if (result == MessageBoxResult.No)
{
e.Cancel = true;
}
}
程式以 Admin 權限執行或者加入 app.manifest 檔案並且設定以下內容:
<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />
以 Admin 權限開啟程式
點選 windows/power/shutdown 關機
如下圖所示 Windows Shutdown 會停止並顯示 Closing x apps and shutting down
按下 Cancel 或 Shut down anyway
a. Cancel: 回到桌面後可以看到 messagebox 跳出警告,按下 YES 會結束該程式,按下 NO 會保留該程式
b. Shut down anyway: 不管其他 Apps 關機