Preliminary study on Windows service

xiaoxiao2021-03-06  23

Author: Wenbin Home: Wenbin network http://www.wenbinweb.com Windows service program is a standalone Windows application user to log in and work, it is usually started when the computer starts, and often performed continuously until the computer turns off until. This approach is used in Exchange Server, IIS and anti-virus software, so you can run independent of a user and you can run in any user, and you can also serve all processes, thereby exists in a service form. . Because Windows services have so many features, you can consider using Windows services to solve problems when you need some special features. For example, this example we have to do. For our programming staff, the computer is a partner working together. Every day, it is more than eight hours of the screen, and it does not include the time after get off work, so protect your eyes is the most important. . The cause of the problem is derived from the Saturday to the Ophthalmology to the laser surgery. The doctor repeatedly emphasized the self-regulatory ability of the eyes, that is, as long as you can guarantee that you will close your eyes every hour, look at it, look at it, leave The computer screen, then the close look will not rebound. Although I am a self-discipline, it is no longer so in front of the computer screen. I often don't look up in a few hours. For the sake of the health, I decided to transfer this arduous task to the computer, let it I automatically remind me for five minutes at around an hour. In this way, don't you use it anymore. Although it is simple, it is not a good way to run automatically in the launch group. It is not as good as a Windows service before, it is not asked to try it. Net also look at .NET to provide us How advanced features, so I decided to use C # to make a reminder that I protect my eyes, name is called Careeye. Run Visual Studio.net 2003, build a C # Windows service project, in the design view prompt of CareEye.cs to drag the required controls and components to this, if you want to do system logs, you can drag EventLog components Come over, but this program doesn't seem to need these things, or you still count. So do you want to use a timer control? Think about it, this control is easy to use, but it is often used, in the principle of learning new knowledge, the most appropriateness is thread, and the thread is definitely necessary when doing other Windows services in the future, so it is still using threads Ok, so I just have to complete the monitoring of time in the thread, start the thread start and stop the startup and stop, huh, very convenient. Let's see the source program of CareEye.cs, a lot of things that have never seen, but carefully analyze it. The Careeye class is derived from the ServiceBase class, so inherits the characteristics of the basic service class, obviously the main () method is called by the SCM (Service Control Manager), in this method, a new CareEye instance, which runs a Windows service OnStart () and onStop () are obviously the response function for starting and stopping the service. Note that there is a servicebase [] in the main () method, which is prepared for those services that contain multiple services. For this program, it only has a CareEye service, so you can delete this array, and Just use system.serviceProcess.serviceBase.Run (New Careeye ()); one sentence is enough.

Next, in order to use threads, you need to introduce System.Threading namespaces. In order to use the dialog, you also need to introduce System.Windows.Forms namespaces, which is prepared to display the dialog box when prompted the user. The following add a member field private Thread MainThread class CareEye; simultaneously initialized in its constructor: MainThread = new Thread (new ThreadStart (ThreadFunc)); MainThread.Priority = ThreadPriority.Lowest; where the priority of a thread set to The lowest, which does not consume too much system performance. This thread object uses ThreadFunc as a thread function, so supplement this thread function complete: public static void threadfunc () {int LastHour = datetime.now.Hour; while (true) {system.threading.thread.sleep (60000); if (DateTime.now.Hour-1 == LastHour) {MessageBox.show ("In order to care for your eyes, please pay for 5 minutes to stay in the distance!", "Warning", MessageBoxButton, MessageBoxDefaultButton.Button1, MessageBoxOptions.defaultDesktoponly; LastHour = datetime.now.hour;}}} The remaining code is simple, as long as the thread is started in OnStart, stop the thread in OnStop. Although the above service procedures are very simple, the process of thread is not very appropriate, but also violates the principles of the service programs such as interface display, but it is sufficient for my demand, so it is so created. If you have a need, of course, you can change the dialog to another reminder such as a ring, etc., threads can also use the kernel object to use a better processing method. Windows service is finished, the rest is to test, but find this EXE unable to 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 Windows service, It registers Windows only. Next, right-click the design view of CareEye.cs, add the installer, (vs.net thinking is quite thoughtful), this is a batch of code, but it doesn't have to change the code, just put the account type of Account. Set to Localsystem, set StartType to start, here, here is manually debugged, and it can be changed to automatic type.

After compilation, it is still unable to run. Here is one step, it is to run installutil to install this service. The usage of its installation and unloading is: installutil caeye.exe installutil / u Careeye.exe after installation, you can pass the system service manager You can see your service, just click the startup, you can turn it out, turn the time an hour it will remind you to rest, huh, huh, simple enough. If you want to make a friend who is sent to yourself, you only need to add a deployment project, but in order to complete the self-registration, you must add a custom installation operation in the installation phase in the custom operation editor, put installerclass The property is set to TRUE. The rest of the thing is to try it yourself. This time you don't have to worry about using your eyes! ! Empty net to Wenbin right into every program it is careeye.cs the following source code: using System; using System.Collections; using System.ComponentModel; using System.Data; using System.Diagnostics; using System.ServiceProcess; using System .Threading; use system.windows.forms; namespace careeye {public class careeye: system.serviceProcess.serviceBase {private thread mainthread; ///

// / / must-have designer variable. /// private system.componentmodel.container components = null;

Public CareEye () {// This call is required for the Windows.Forms component designer. InitializationComponent ();

// Todo: Add any initialization MainThread = New Thread (New Threadstart (threadfunc)); mainthread.priority = threadpriority.lowest;}

// The main entry point static void main () {//system.serviceProcess.serviceBase [] ServicesTorun; // You can run multiple user services in the same process. To add // another service to this process, change the downlink // to create another service object. For example, //// serviceStorun = new system.serviceProcess.serviceBase [] {new careeye (), new myseconduserService ()}; //////// serviceProcess.serviceBase [] {new careeye ()};

System.ServiceProcess.serviceBase.Run (New Careeye ());

///

/// Designer supports the required method - do not use the code editor // / to modify the contents of this method. /// private void initializecomponent () {/// Careeye // this.ServiceName = "Careeye";

}

///

/// Clean all the resources being used. /// Protected Override Void Dispose (Bool Disposing) {if (disponents! = Null) {components.dispose ();}} Base.Dispose (4);

///

/// sets the specific operation so that the service can perform its work. /// protected override void onstart (String [] args) {// Todo: Add code to start the service. MAINTHREAD.START ();} /// /// stop this service. /// protected override void onstop () {// TODO: Add code here to perform the shutdown operation required 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 ( "! in order to take good care of your eyes, you take a short break and five minutes away overlooking", "warning", MessageBoxButtons.OK, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button1, MessageBoxOptions.DefaultDesktopOnly); LastHour = DateTime.now.hour;}}}}}}

转载请注明原文地址:https://www.9cbs.com/read-77248.html

New Post(0)