C # Windows Services

Source: Internet
Author: User

The first two days the company is going to do a Windows service and want me to provide next. The right to do a shell now share with you:

1. Open vs (My is 2010), create a new project select "Window Service":

2. Right-click on "Service1.cs Design" and select "Add Installer":

3. Set ServiceName to "Servicetest" in "Service1.cs Design" (the user can define it yourself), then select ServiceInstaller1 ServiceName set to the previous "Service1.cs Design, there are several property settings:

The role of these attributes is not described, to understand.

Next, select ServiceProcessInstaller1 to set the properties:

Ok, now it's a job to write a service.

Right-click on "Service1.cs Design" to view the code, open

This is the user to write their own logic, I do not describe it.

Well, now the service is written to the installation.

Create a new window Form program, I will not post the new diagram directly to see the final picture:

Now it's the code:

        private void Btninstall_click (object sender, EventArgs e) {if (! Serviceisexisted ("Servicetest")) {try {string currentdirecto                    ry = System.Environment.CurrentDirectory;                    System.Environment.CurrentDirectory = currentdirectory + "\\Service";                    Managedinstallerclass.installhelper (new string[] {"WindowsServiceTest.exe"});                    System.Environment.CurrentDirectory = CurrentDirectory;                Labeltooptip.text = "Installation successful!"; } catch (Exception ex) {labeltooptip.text = "Installation error:" + ex.                Message;                        }} else {labeltooptip.text = "The service is already installed, please uninstall it if you need to reinstall!"; }} private void Btnuninstall_click (object sender, EventArgs e) {if (Serviceisexi            Sted ("Servicetest")) {    try {string currentdirectory = System.Environment.CurrentDirectory;                    System.Environment.CurrentDirectory = currentdirectory + "\\Service";                    Managedinstallerclass.installhelper (new string[] {"/U", "WindowsServiceTest.exe"});                    System.Environment.CurrentDirectory = CurrentDirectory;                Labeltooptip.text = "Uninstall succeeded!"; } catch (Exception ex) {labeltooptip.text = "Unload error:" + ex.                Message;            }} else {labeltooptip.text = "The service you want to uninstall does not exist!";                }} private void btnStart_Click (object sender, EventArgs e) {try {                ServiceController ServiceController = new ServiceController ("Servicetest");                Servicecontroller.start ();            Labeltooptip.text = "Service started successfully!"; } catch (Exception ex) {labeltooptip.text = "service startup error:" + ex.            Message;                }} private void Btnstop_click (object sender, EventArgs e) {try {                ServiceController ServiceController = new ServiceController ("Servicetest");                if (servicecontroller.canstop) servicecontroller.stop ();            Labeltooptip.text = "Service stopped successfully!"; } catch (Exception ex) {labeltooptip.text = "Service Stop error:" + ex.            Message; }} private bool Serviceisexisted (string svcname) {servicecontroller[] services = Service            Controller.getservices ();                    foreach (ServiceController s in services) {if (S.servicename = = Svcname) {                return true;        }} return false;  }

Here is basically OK, but there is another problem is that the program must be run by the administrator, so in the Form program Program.cs add a piece of code, the following code:

  Static voidMain () {application.enablevisualstyles (); Application.setcompatibletextrenderingdefault (false); /** * When the current user is an administrator, start the application directly * if it is not an administrator, use the Startup Object Launcher to ensure that you are running with Administrator*/            //get the currently logged in Windows User logoSystem.Security.Principal.WindowsIdentity identity =System.Security.Principal.WindowsIdentity.GetCurrent (); System.Security.Principal.WindowsPrincipal Principal=NewSystem.Security.Principal.WindowsPrincipal (identity); //determine whether the currently logged on user is an administrator            if(Principal. IsInRole (System.Security.Principal.WindowsBuiltInRole.Administrator)) {//If it is an administrator, run it directlyApplication.Run (NewForm1 ()); }            Else            {                //To Create a startup objectSystem.Diagnostics.ProcessStartInfo StartInfo =NewSystem.Diagnostics.ProcessStartInfo (); Startinfo.useshellexecute=true; Startinfo.workingdirectory=environment.currentdirectory; Startinfo.filename=Application.executablepath; //set the start action to ensure that you are running as an administratorStartinfo.verb ="runas"; Try{System.Diagnostics.Process.Start (startinfo); }                Catch                {                    return; }            }        }

Now it's done. The test is as follows:

Here I declare, I also read some people on the Internet to complete the information, then did not record the person's website, here first thank others for information.

If there is a problem or better deal with the welcome advice!

Attached source code:

Http://files.cnblogs.com/files/startlearn/WindowsServiceTest.zip

C # Windows Services

Related Article

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.