Write a service that detects once in 5 minutes, whether a process is started or not, and if it is not, the process is started

Source: Internet
Author: User

  Public Partial classService1:servicebase { PublicService1 () {InitializeComponent (); }        protected Override voidOnStart (string[] args) {System.Timers.Timer timer1=NewSystem.Timers.Timer (); Create a timer timer1. Interval= +* -*5;//5min Execution OnceTimer1. Elapsed + =timer1_elapsed; Timer1. Enabled=true; Timer1.            Start (); stringOpe ="Start the service";            Saverecord (Ope);        StartServer (); }        Private voidTimer1_elapsed (Objectsender, System.Timers.ElapsedEventArgs e) {            stringOpe ="Start the service";            Saverecord (Ope);        StartServer (); }        Private voidStartServer () {process[] processes= Process.getprocessesbyname ("IExplore");//Process Name            if(Processes = =NULL|| Processes. Length = =0) {Process myprocess=NewProcess (); Try{MyProcess.StartInfo.UseShellExecute=false;//whether to start the process using the operating system shellMyProcess.StartInfo.FileName ="C:\\Program Files\\Internet Explorer\\iexplore.exe";//Process PathMyProcess.StartInfo.CreateNoWindow =true;//whether to start the value of the process in a new windowMyprocess.start ();//to start the process component's Process.startinfo property for the specified processes resource                }                Catch(Exception e) {Console.WriteLine (e.message); }            }        }        Private voidSaverecord (stringope) {            using(FileStream fs =NewFileStream ("E:\\log.txt", Filemode.append, FileAccess.Write)) {                using(StreamWriter SW =NewStreamWriter (FS, Encoding.default)) {SW. WriteLine (DateTime.Now.ToString ("YYYY-MM-DD HH:mm:ss") +ope); }            }        }        protected Override voidOnStop () {stringOpe ="Stop Service";        Saverecord (Ope); }    }

After the creation is finished, you need to install the service to the computer.

The simplest way to install a service:

1. C:\\window\microsoft. Net\ ... 4.5 (3.5,4.0) below InstallUtil.exe and InstallUtilLib.dll copied to the service project Bin\Debug directory

2. Create a new TXT file, enter InstallUtil (-e) WindowsService1.exe Save as Install.bat, and then double-click the file to install the service.

3.1 Enter Services.msc to view the service, find the service just installed, start on it.

3.2 or under CMD, enter the net start service name. such as: net start Service1

The simplest way to uninstall a service: (It's a good idea to stop the service before you uninstall net stop Service1)

1. C:\\window\microsoft. Net\ ... 4.5 (3.5,4.0) below InstallUtil.exe and InstallUtilLib.dll copied to the service project Bin\Debug directory

2. Create a new TXT file, enter Installutil-u WindowsService1.exe Save as Uninstall.bat, and then double-click the file to uninstall the service.

3 Enter Services.msc View service and you can see that the uninstalled service is gone.

Installation and uninstallation services can also be written to a C # program:


Once written to a C # program, running the. exe file directly is OK.

classProgram {Static voidMain (string[] args)            {application.enablevisualstyles (); Application.setcompatibletextrenderingdefault (false); stringSysdisk = System.Environment.SystemDirectory.Substring (0,3); stringDotnetpath = Sysdisk +@"Windows\microsoft.net\framework\v4.0.30319\installutil.exe";//. net4.0 's Environment            stringServiceexepath = Application.startuppath +@"\windowsservice1.exe";//exe file, place the exe file of the service under the bin of this project            stringServiceinstallcommand =string. Format (@"{0} {1}", Dotnetpath, Serviceexepath);//DOS commands to use when installing services            stringServiceuninstallcommand =string. Format (@"{0}-u {1}", Dotnetpath, Serviceexepath);//DOS commands to use when uninstalling a service            Try            {                if(File.exists (Dotnetpath)) {string[] cmd =New string[] {Serviceuninstallcommand,"net stop Service1" }; stringSS =cmd (cmd); Closeprocess ("Cmd.exe"); }            }            Catch{} thread.sleep ( +); Try            {                if(File.exists (Dotnetpath)) {string[] cmd =New string[] {Serviceinstallcommand};//{serviceinstallcommand, "net start Service1"} can be started directly in CMD or                    stringSS =cmd (cmd); Closeprocess ("Cmd.exe"); }            }            Catch            { }            Try{Thread.Sleep ( the); ServiceController SC=NewServiceController ("Service1"); //determines the current state of the service and starts if it is not started.                 if(SC! =NULL&& (SC. Status.equals (servicecontrollerstatus.stopped)) | |(SC. Status.equals (servicecontrollerstatus.stoppending))) {SC.                Start (); } SC.            Refresh (); }            Catch(Exception e) {Console.WriteLine (e.message);} }        Private Static BOOLCloseprocess (stringprocname) {            BOOLresult =false; System.Collections.ArrayList proclist=NewSystem.Collections.ArrayList (); stringTempname =""; intBegpos; intEndpos; foreach(Process Iteminchprocess.getprocesses ()) {Tempname=item.                ToString (); Begpos= Tempname.indexof ("(") +1; Endpos= Tempname.indexof (")"); Tempname= Tempname.substring (Begpos, Endpos-Begpos);                Proclist.add (Tempname); if(Tempname = =procname) {                    if(!item. CloseMainWindow ()) item. Kill ();//forcibly end a process when the Send close Window command is invalid                    return true; }            }            returnresult; }        Private Static stringCMD (string[] cmd) {Process P=NewProcess (); p.StartInfo.FileName="Cmd.exe"; P.startinfo.useshellexecute=false; P.startinfo.redirectstandardinput=true; P.startinfo.redirectstandardoutput=true; P.startinfo.redirectstandarderror=true; P.startinfo.createnowindow=true;            P.start (); P.standardinput.autoflush=true;  for(inti =0; I < cmd. Length; i++) {p.standardinput.writeline (Cmd[i].            ToString ()); } p.standardinput.writeline ("Exit"); stringStrrst =P.standardoutput.readtoend ();            p.WaitForExit ();            P.close (); returnStrrst; }    }

Write a service that detects once in 5 minutes, whether a process is started or not, and if it is not, the process is started

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.