代码之家  ›  专栏  ›  技术社区  ›  scrat789

如何从windows服务c取消关机#

  •  1
  • scrat789  · 技术社区  · 14 年前

    我启动了一个windows服务(用c.net2.0编写)。

    我想检测计算机何时关闭/重新启动并取消它。 取消后,我想做一些操作并重新启动Windows。

    我试过了,但没用

    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();
        }
    }
    
    6 回复  |  直到 14 年前
        1
  •  4
  •   Neil Barnwell    14 年前

    我可不想搞砸。Windows会将您的进程视为挂起的进程(除非您直接转到win32 api)。

    我的建议是注意到你正在关机,也许可以安排启动时的活动?

    更新:
    我想你会被困在这里,因为你的服务不知道 为什么? Windows正在关闭。你将有一个无限循环:

    • Windows关闭激发。
    • 服务通知,中止关机,启动应用程序。
    • 用户使用应用程序继续关机。
    • 窗口关闭触发。
    • 服务通知……
    • 等。
        2
  •  1
  •   James    14 年前

    我的建议是把你的行为写进一个文件或注册表。

    DoSomething = true
    DoSomethingElse = false
    

    你可以读入 OnStart 和过程。

        3
  •  1
  •   Vinz    14 年前

    可以使用shell命令 shutdown -a 中止关机。我不知道是否有可能检测到关机…

        4
  •  1
  •   scrat789    14 年前

    最后我放弃了检测和取消windows关闭/重新启动的想法, 但现在我 只想检测“关机-r-t xx” !

    请注意运行该程序的操作系统是Windows XP。

    我试过了,但是我没有WindowsXP的退出代码:

    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) ;
    
        5
  •  1
  •   scrat789    14 年前

    解决方案是使用winform检测关机: http://msdn.microsoft.com/fr-fr/library/microsoft.win32.systemevents.sessionending%28VS.80%29.aspx

    但是windows在我发现它之前就杀死了其他进程,所以这不是更好的解决方案!

        6
  •  1
  •   Hans Olsson    14 年前

    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();
    }