Timer timer1 = new Timer(); protected override void OnStart(string[] args) { try { //Debugger.Break(); TraceService("Start Service" + " " + DateTime.Now.ToString()); //timer1.Interval = 1000; timer1.Elapsed += new ElapsedEventHandler(OnElapsedTime); timer1.Enabled = true; //Debugger.Break(); } catch (Exception ex) { TraceService("Error: " + ex); //EventLog.WriteEntry("Error: " + ex.Message); } } private void OnElapsedTime(object source, ElapsedEventArgs e) { try { //timer1.Stop(); //Debugger.Break(); timer1.Enabled = false; TraceService("Another entry at" + " " + DateTime.Now); //TraceService("System shutdown Sucessfully" + " " + DateTime.Now.ToString()); timer1.Enabled = true; //WindowsServiceSchedular(timer1); } catch (Exception ex) { EventLog.WriteEntry("Error: " + ex.Message); TraceService("Error: " + ex); } } private void TraceService(string content) { try { if (!Directory.Exists(@"C:\SystemShutdown\SystemShutdownLogFile")) Directory.CreateDirectory(@"C:\SystemShutdown\SystemShutdownLogFile"); FileStream fs = new FileStream(@"C:\SystemShutdown\SystemShutdownService.Txt", FileMode.OpenOrCreate, FileAccess.ReadWrite); StreamWriter sw = new StreamWriter(fs); sw.BaseStream.Seek(0, SeekOrigin.End); sw.WriteLine(content); sw.Flush(); sw.Close(); } catch (Exception ex) { EventLog.WriteEntry("Error: " + ex.Message); } } protected override void OnShutdown() { TraceService("System shutdown"); //I want to run exe in this function but firstly message is not coming when i am shutting down the computer. base.OnShutdown(); } protected override void OnCustomCommand(int command) { base.OnCustomCommand(command); } protected override void OnStop() { timer1.Stop(); TraceService("Stop Service"); }
Quote:Launching a process when the shutdown was initiated is a bad idea. At this stage the most likely outcome is to get back the error 1115 ERROR_SHUTDOWN_IN_PROGRESS. A much better way is to install a service and register the service to receive shutdown notifications via RegisterServiceCtrlHandlerEx, see shutting down: Service applications receive shutdown notifications in their handler routines. To register a service control handler, use the RegisterServiceCtrlHandlerEx function. A C# service would do this by setting CanShutdown to true and then handling the OnShutdown event. It is important to be service, not an application, as shutdown can occur when no session is logged on and/or multiple sessions could be running when the shutdown occurs.
var
This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)