Windows service is a Windows application that runs independently of a logon user. 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; } } } |
The remaining code is simple. You only need to 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.
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:
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 rest is to try it by yourself. Don't worry about timeout this time!
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. |