2010-04-27 69 views
1

我有一個Windows服務啓動(用C#.net2.0編寫)。如何從Windows服務C取消關閉#

我想檢測何時電腦關機/重啓並取消它。 取消後我想要做一些操作並重新啓動窗口。

我已經嘗試過了,但它不工作

using Microsoft.Win32; 
partial class MyService: ServiceBase 
{ 
    protected override void OnStart(string[] args) 
    { 
     SystemEvents.SessionEnding += new SessionEndingEventHandler(OnSessionEnding); 
    } 

    private void OnSessionEnding(object sender, SessionEndingEventArgs e) 
    { 
     e.Cancel = true; 
     //Do some work... 
    } 
} 

另一項測試:

partial class MyService: ServiceBase 
{ 
    protected override void OnShutdown() 
    { 
     //Do some work... 
     //base.OnShutdown(); 
    } 
} 

回答

4

我不會亂用這個。 Windows將把你的進程視爲一個掛起的進程(除非你直接進入Win32 API)。

我的建議是注意你正在關機,也許安排在啓動時發生的活動?

UPDATE:
我想你會得到困在這裏了,因爲你的服務就不會知道爲什麼 Windows已被關閉。你將有一個無限循環:

  • Windows關閉火災。
  • 服務通知,中止關機,啓動應用程序。
  • 用戶使用應用程序繼續關機。
  • 窗口關閉火災。
  • 服務的通知......
  • 等等
+0

我不能在啓動時進行我的活動,因爲我想在用戶登錄/關機/重新啓動時從我的Windows服務中午吃一個winform應用程序。 我的winform應用程序有一個「立即重新啓動」按鈕,和另一個「提醒我後者」,並做一些其他工作... – scrat789 2010-04-27 10:07:58

+0

@scrat:另一個不,不是,Windows服務不建立,不應該使用用於與GUI交互。 – James 2010-04-27 10:44:13

+0

@James他*確實*說他的服務將啓動另一個應用程序,但是。 – 2010-04-27 11:23:44

1

我的建議是寫你的行動到一個文件或如註冊表

DoSomething = true 
DoSomethingElse = false 

你可以在OnStart和過程中看到。

1

AbortSystemShutdown可能的工作:

http://msdn.microsoft.com/en-us/library/aa376630%28VS.85%29.aspx

雖然我同意尼爾,這可能不是一個好主意,這樣做。

編輯:添加代碼示例

using System.Runtime.InteropServices; 

[DllImport("advapi32.dll", SetLastError=true)] 
static extern bool AbortSystemShutdown(string lpMachineName); 


if (!AbortSystemShutdown("localhost")) 
{ 
    int err = Marshal.GetLastWin32Error(); 
}   
+0

如何在C#中使用AbortSystemShutdown函數? – scrat789 2010-04-27 10:02:58

+0

使用PInvoke。這裏有一些關於它的信息http://www.pinvoke.net/default.aspx/advapi32/AbortSystemShutdown.html – 2010-04-27 10:08:13

+0

它的老,但沒有人有這個請完整的代碼示例?我無法找到任何C#與谷歌。只是不太明白在我的代碼中使用每個示例行的位置。我的意思是我不知道把DllImport部分放在哪裏以及在哪裏使用if()語句來攔截。提前致謝。 – user3916429 2015-05-22 05:03:02

1

你可以使用shell命令shutdown -a中止關機。我不知道是否有可能檢測到關機雖然...

1

最終我放棄檢測和取消窗口關機/重新啓動, 的想法但現在我想只需檢測「關閉-r -t xx」

請注意,運行程序的操作系統是Windows XP。

我有嘗試,但我有WindowsXP中沒有的ExitCode:

Process process = new Process(); 

do 
{ 
    process.StartInfo.FileName = "shutdown.exe"; 
    process.StartInfo.Arguments = "/a"; 
    process.Start(); 
    process.WaitForExit(); 
    MessageBox.Show(string.Format("ExitCode={0}",process.ExitCode)); 
    Thread.Sleep(1000); 
} 
while (process.ExitCode != 0) ; 
+0

我已經修改了我的答案上面的實際示例代碼這應該有希望工作,所以你不必開始這個過程。 – 2010-04-28 09:32:30

+0

@ho在我能夠檢測到關機之前,Windows會終止其他進程,因此它不是更好的解決方案。 我決定在「shutdown -r -t xx」此時停止啓動我的程序時檢測超時窗口。 – scrat789 2010-04-28 13:04:56

+0

在「shutdown -r -t xx」之後檢測超時窗口的解決方案基於檢測窗口的標題: http://www.pinvoke.net/default.aspx/user32.EnumWindows – scrat789 2010-04-28 13:09:13