In Visual C #, how do I create and call Windows Services?

Source: Internet
Author: User
Windows service is a Windows application that works independently of logon users. Program It is usually executed continuously when the computer is started until the computer is shut down. Such methods as exchange server, IIS, and anti-virus software are used, so that they can run independently of a user and can be used by any user to log on, and also to serve all processes, therefore, it exists as a service.

Because Windows Services have so many features, you can consider using Windows Services to solve the problem when you need some special features. For example, the following is an example. For our programmers, computers are the longest-working partners, and they face their screens for more than eight hours every day, not including playing games at home after work. Therefore, protecting your eyes is the most important thing. The cause of the problem is that I went to the Ophthalmology Department on Saturday to review the laser operation. The doctor repeatedly stressed to me the self-regulating ability of the eyes, that is to say, as long as you can ensure that you close your eyes or look into the distance every other hour or so and leave the computer screen, the cured myopia will not rebound. Although I am a self-disciplined person, but in front of the computer screen is no longer so, often a few hours do not look up once, for the sake of eye health, I decided to hand over the difficult task to the computer and asked it to automatically remind me to take a five-minute break in about an hour. In this way, I don't have to worry about it any more.

Although the function is simple, it is not a good way to write a program to be automatically run in the startup group every day. It happened that Windows Services have never been used before. It is better to simply give it a try. net provided us with so advanced functions, so I decided to use C # To make a Windows service that reminds me to protect my eyes. It was named careeye.

Run Visual Studio. NET 2003, create a C # Windows Service Project in careeye. the CS design view prompts you to drag the required controls and components to the above. If you want to make system logs, you can drag the EventLog component, however, this program does not seem to need these things. Forget it. Do you want to use the timer control for timing? I thought for a moment, although this control is easy to use, it is too often used. In the principle of learning new knowledge, the most appropriate thing is probably the thread, in addition, the thread is required when other Windows Services are used in the future, so it is better to use the thread, So that I only need to monitor the time in the thread, it is very convenient to give the start and stop of the thread to the start and stop of the service.

Let's take a look at the source program of careeye. cs. There are a lot of things you have never seen before, but it's okay to analyze them carefully. The careeye class is derived from the servicebase class, so it inherits the features of the basic service class. Obviously, the main () method is called by SCM (Service Control Manager, in this method, run a new careeye instance to run a Windows service. onstart () and onstop () are obviously the response functions used to start and stop the service.

Note that there is an array of servicebase [] in the main () method. It is prepared for a service process that contains multiple services. For this program, there is only one careeye service, therefore, you can delete this array, instead of using system. serviceprocess. servicebase. run (New careeye (); one sentence is enough.

To use the thread, You need to introduce the system. Threading namespace. To use the dialog box, you also need to introduce the system. Windows. Forms namespace, which is prepared to display the dialog box when users are prompted in the future.

Add a member field private thread mainthread for the careeye class and initialize it in the constructor:

Mainthread = new thread (New threadstart (threadfunc ));
Mainthread. Priority = threadpriority. Lowest;

Set the thread priority to the lowest level, so that the system performance will not be consumed too much. This thread object uses threadfunc as the thread function, so the thread function is supplemented completely:

Public static void threadfunc ()
{
Int lasthour = datetime. Now. hour;
While (true)
{
System. Threading. thread. Sleep (60000 );
If (datetime. Now. Hour-1 = lasthour)
{
MessageBox. Show ("to take good care of your eyes, please take a 5-minute break and look into the distance! "," Warning ", messageboxbuttons. OK, messageboxicon. Warning, messageboxdefaultbutton. button1,
Messageboxoptions. defaulttopics toponly );
Lasthour = datetime. Now. hour;
}
}
}

Remaining Code Simply start the thread in onstart and stop the thread in onstop.

Although the above service programs are very simple, the thread processing is not very appropriate, but also violates the principles of many service programs, such as interface display, etc., but it is sufficient for my own needs, so it was created. If you need it, you can change the dialog box to other reminder methods, such as ringing. The thread can also use the kernel object to use better processing methods at the same time.

The Windows service is complete, and the rest is to test, but the EXE cannot run, it will prompt you to use the installer to install the service, it seems that it is impossible to write a program, even if it is a Windows service, it must be registered to Windows.

In this case, add a new installation program class, installer2.cs, and add two components in the toolbox: serviceinstaller and serviceprocessinstaller, and modify and select the attributes of the two components.

Next, right-click careeye. in the CS design view, add the installer (. net is very thoughtful), and now a batch of code is coming out, but fortunately you don't need to change the code. You just need to set the Account type to LocalSystem and set starttype to manual start, here, manual debugging is used to facilitate debugging. You can change it to automatic type later.

After compilation, it still cannot be run. Another step is to run installutil to install the service. Its installation and uninstallation usage is as follows:

// C: \ WINDOWS \ microsoft. Net \ framework \ v2.0.50727 \ installutil.exe or use the vs command console
Installutil careeye.exe
Installutil/u careeye.exe

After the installation, you can see your service through the system service manager. You only need to click Start to start it, if you change the time to an hour, it will remind you to take a rest.

If you want to create an installation package and distribute it to your friends, you only need to add a deployment project. However, to complete self-registration, to add a custom installation operation in the installation phase of the custom operation Editor, set the installerclass attribute to true.

The following is the source program of careeye. CS:

Using system;
Using system. collections;
Using system. componentmodel;
Using system. Data;
Using system. diagnostics;
Using system. serviceprocess;
Using system. Threading;
Using system. Windows. forms;
Namespace careeye
{
Public class careeye: system. serviceprocess. servicebase
{
Private thread mainthread;
/// <Summary>
/// Required designer variables.
/// </Summary>
Private system. componentmodel. Container components = NULL;

Public careeye ()
{
// This call is required by the windows. Forms component designer.
Initializecomponent ();

// Todo: add any initialization after the initcomponent call
Mainthread = new thread (New threadstart (threadfunc ));
Mainthread. Priority = threadpriority. Lowest;
}

// Master entry point of the process
Static void main ()
{
// System. serviceprocess. servicebase [] servicestorun;

// Multiple user services can be run in the same process. To
// Add another service to this process. Change the downstream service.
// Create another service object. For example,
//
// Servicestorun = new system. serviceprocess. servicebase [] {New careeye (), new myseconduserservice ()};
//
// Servicestorun = new system. serviceprocess. servicebase [] {New careeye ()};

System. serviceprocess. servicebase. Run (New careeye ());
}

/// <Summary>
/// The designer supports the required methods-do not use the code editor
/// Modify the content of this method.
/// </Summary>
Private void initializecomponent ()
{
//
// Careeye
//
This. servicename = "careeye ";

}

/// <Summary>
/// Clear all resources in use.
/// </Summary>

Protected override void dispose (bool disposing)
{
If (disposing)
{
If (components! = NULL)
{
Components. Dispose ();
}
}
Base. Dispose (disposing );
}

/// <Summary>
/// Set specific operations so that the service can perform its work.
/// </Summary>
Protected override void onstart (string [] ARGs)
{
// Todo: Add code here to start the service.
Mainthread. Start ();
}

/// <Summary>
/// Stop the service.
/// </Summary>
Protected override void onstop ()
{
// Todo: Add code here to stop the service.
Mainthread. Abort ();
}
Public static void threadfunc ()
{
Int lasthour = datetime. Now. hour;
While (true)
{
System. Threading. thread. Sleep (60000 );
If (datetime. Now. Hour-1 = lasthour)
{
MessageBox. Show ("to take good care of your eyes, please take a 5-minute break and look into the distance! "," Warning ", messageboxbuttons. OK, messageboxicon. Warning, messageboxdefaultbutton. button1, messageboxoptions. defaulttoptoponly );
Lasthour = datetime. Now. hour;
}
}
}
}
}

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.