C# development of Windows service with a simple example of the realization of QQ

Recommended for you: Get network issues from WhatsUp Gold. Not end users.

This example to achieve three major basic functions of the following

1,C#The development of windows service

2,QQ program running prohibited

3,Create an automated setup for Windows Services

On the three basic functions

A, C# windows service development

Windows services is called NT service in previous versions of VS, in the VS.NET enabled new name. To create a Windows service using C# is not a difficult thing, the next page for service creation, start, stop doing detailed introduction

1,First add a WinForm program KillService in VS

2,The addition of Windows service in the new item in solution

3,Open the services page, switch to code page has the following two methods:

protected override void OnStart(string[] args)
{
   // Add TODO: code here to start the service. 
}
protected override void OnStop()
{
// Add TODO: code here to implement stop service needed for closing operation. 
}

When the service starts after the general will require every few seconds or a few minutes to refresh a data, so to use a timer, timer inside for business operations. The windows service cannot directly in VS under the debugger, so you can choose to use a variety of log service start stop or abnormal state. The concrete realization of the code are as follows:

partial class Service1 : ServiceBase
    {
        static System.Timers.Timer oTimer_Get = new System.Timers.Timer();
        public Service1()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {
            // Add TODO: code here to start the service. 
            AutoLog = false;
            FileLog.Success("The service is started");
            oTimer_Get.Enabled = true;
            oTimer_Get.Interval = 10000;
            oTimer_Get.Elapsed += new System.Timers.ElapsedEventHandler(OnTimedEvent);
        }
        private void OnTimedEvent(object sender, System.Timers.ElapsedEventArgs e)
        {
            FileLog.Success("Start sending");
            oTimer_Get.Enabled = false;
            try
            {
                //Here to write detailed business operation
            }
            catch (Exception ex)
            {
                FileLog.Error(ex.Source + ". " + ex.Message);
            }
            oTimer_Get.Enabled = true;
            FileLog.Success("Stop sending");
        }
        protected override void OnStop()
        {
            // Add TODO: code here to implement stop service needed for closing operation. 
            FileLog.Success("The service has been stopped");
            oTimer_Get.Enabled = false;
        }
    }

Document class code

/// <summary>
    /// Log file type
    /// </summary>
    public static class FileLog
    {
        private static string sFilePath = System.Configuration.ConfigurationSettings.AppSettings["UserLog"];
        /// <summary>
        /// The error log
        /// </summary>
        /// <param name="Message">The error</param>
        public static void Error(string Message)
        {
            try
            {
                if (!Directory.Exists(sFilePath))
                {
                    Directory.CreateDirectory(sFilePath);
                }
                string sFileName = sFilePath + "\\" + string.Format("{0}-Error.txt", DateTime.Now.ToString("yyyy-MM-dd"));
                string sContent = string.Format("{0}-- {1}\r\n", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), Message);
                FileStream fs = new FileStream(sFileName, FileMode.Append);
                Byte[] b = Encoding.Default.GetBytes(sContent);
                fs.Write(b, 0, b.Length);
                fs.Close();
            }
            catch { }
        }
        /// <summary>
        /// The correct log
        /// </summary>
        /// <param name="Message">The right content</param>
        public static void Success(string Message)
        {
            try
            {
                if (!Directory.Exists(sFilePath))
                {
                    Directory.CreateDirectory(sFilePath);
                }
                string sFileName = sFilePath + "\\" + string.Format("{0}-Success.txt", DateTime.Now.ToString("yyyy-MM-dd"));
                string sContent = string.Format("{0}-- {1}\r\n", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), Message);
                FileStream fs = new FileStream(sFileName, FileMode.Append);
                Byte[] b = Encoding.Default.GetBytes(sContent);
                fs.Write(b, 0, b.Length);
                fs.Close();
            }
            catch { }
        }
    }

4,Services need a boot entrance, open the program.cs file to write code in the main function inside the entrance.:

static class Program
    {
        /// <summary>
        /// The main entrance point for the application. 
        /// </summary>
        [STAThread]
        static void Main()
        {
            ServiceBase[] ServicesToRun;
            ServicesToRun = new ServiceBase[] { 
              new Service1() 
            };
            ServiceBase.Run(ServicesToRun);
        } 
    }  

This windows service is completed, but no operation function of the service now. Next, forbid the machine QQ program running function

Two, QQ program running prohibited

Is just to get the machine running all, through the Process.kill () method to the end of the process.

Process[] process = Process.GetProcesses();
                for (int i = 0; i <process.Length; i++)
                {
                    if (process[i].ProcessName == "QQ")
                    {
                        process[i].Kill();
                    }
                }

The operation on the operation module to windows services in the.

Three, create automatic setup for Windows Services

To achieve the above windows service business operation for the windows service, the following create automatic setup,

1,Switch to the service.cs page, right-click and choose add installer

2,This project will add a new class ProjectInstaller and two mounting components ServiceProcessInstaller and ServiceInstaller, and the service attribute value is copied into the assembly.

3,To determine how to start the service, please right-click the ServiceInstaller1 property and the StartType property is set to the appropriate values.

Manual

The service is installed, you must manually start. Automatic

When the computer restarts, the service will start automatically. Disabled

The service could not be started.

4,The Account properties of the serviceProcessInstaller class to LocalSystem, whether in the system which the user login, the service will start.

Setup the windows service has been completed. By selecting the menu generation from generation to produce the project.

Note that the     do not press F5 key to run the project — — cannot run a service project in this way.

5,Create a startup and stop the file

Install file Install.bat is implemented as follows:

cd %SystemRoot%\Microsoft.NET\Framework\v4.0.30319\installutil.exe KillService.exe

Net Start computer services

SC config automatically killing the service start= Auto 

KillService.exe is the path you generate the executable file

Automatic killing service is the name of the windows service

To stop the file Uninstall.bat file as follows:

%SystemRoot%\Microsoft.NET\Framework\v4.0.30319\installutil.exe /u KillService.exe

KillService.exe is the path you generate the executable file

PS: When these two files in the success, must &ldquo execution; run as administrator ” otherwise, the service startup error

If the service was installed successfully, can in the resource manager service view into the running of the computer services.

Thus the whole case basically completed

This example is for development, learning the Windows service startup, stop. The specific business function is adjusted according to the requirements, such as timing acquisition to add new data from the WebService interface in demand

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download

Posted by Emily at November 14, 2013 - 10:40 AM