preparatory work:0. Computer--management, local Users and Groups, group->administrator double-click Membership--Add network service->Determine1. Start Windows services Windows Installer2. Create a WinForm project WindowsFormsApplication13. Add the Windows service Service14. Add codeprotected Override voidOnStart (string[] args) { if(Args! =NULL&& args. Length >0) { if(args[0] =="1") { stringPath = $@"d:\kxbbbb{datetime.now.tolongdatestring ()}.txt"; File.create ($"{path}"); } Else if(args[0] =="2") { stringPath = $@"d:\kxqqq{datetime.now.tolongdatestring ()}.txt"; File.create ($"{path}"); } } //TODO: Add code here to start the service. }5. Main function Start/// <summary> ///The main entry point for the application. /// </summary>[STAThread]Static voidMain () {//Application.enablevisualstyles (); //Application.setcompatibletextrenderingdefault (FALSE); //Application.Run (New Form1 ());servicebase[] Servicerun; Servicerun=NewServicebase[] {NewService1 ()}; Servicebase.run (Servicerun); }6. Service1.cs Right-click to view the designer and right-click Add Installer, add two ServiceInstaller1 and serviceProcessInstaller1 by default7. ServiceInstaller1 Right-click Property Modify description for this is a test service8. ServiceProcessInstaller1 right-click Property account modified to NetworkService9The . Administrator opens CMDCD C:\Windows\Microsoft.NET\Framework\v4.0.30319Ten. Installation Services InstallUtil.exe WindowsFormsApplication1.exe One. WebForm callsprotected voidPage_Load (Objectsender, EventArgs e) {ServiceController service=NewServiceController ("Service1"); //if (service. Status = = System.ServiceProcess.ServiceControllerStatus.Stopped)//{ //service. Start ();//Open Service//} //Stop ServiceService. Stop ();//This line error: Unable to open the computer "." On the Service1 service. service. WaitForStatus (servicecontrollerstatus.stopped); //Start the service string[] args = {"2" }; Service. Start (args); Service. WaitForStatus (servicecontrollerstatus.running); }
WebForm Calling the Windows service