For introduction to WIndows Services, I have previously written an article: http://blog.csdn.net/yysyangyangyangshan/article/details/7295739. It may not be very detailed about how to write a service. Now we will introduce how to develop and install windows Services in the form of code.
Development Environment: Win7 32-bit; tool: visualstudio2010.
The. net environment comes with Windows 7. Because both manual installation and program installation are required. C: \ Windows \ Microsoft. NET \ Framework, if your code is. net2.0: C: \ Windows \ Microsoft. NET \ Framework \ v2.0.50727; 4.0: C: \ Windows \ Microsoft. NET \ Framework \ v4.0.30319.
Let's take a look at the code below:
1. Create a windows Service
Create a Windows Service
650) this. width = 650; "src =" http://www.bkjia.com/uploads/allimg/131228/15562121O-0.jpg "title =" windowsservice 01.jpg "/>
Enter the program
650) this. width = 650; "src =" http://www.bkjia.com/uploads/allimg/131228/1556216135-1.jpg "title =" Windows Service 02.jpg "/>
The blank service is as follows:
public partial class Service1 : ServiceBase { System.Threading.Timer recordTimer; public Service1() { InitializeComponent(); } protected override void OnStart(string[] args) { } protected override void OnStop() { } }
You only need to complete your function code in OnStart. In this example, we create a function to regularly write records to local files.
650) this. width = 650; "src =" http://www.bkjia.com/uploads/allimg/131228/15562144A-2.jpg "title =" windowsservice 03.jpg "/>
Create a class for users to write files,
Public class FileOpetation {// <summary> // save it to a local file /// </summary> /// <param name = "ETMID"> </param>/ // <param name = "content"> </param> public static void SaveRecord (string content) {if (string. isNullOrEmpty (content) {return;} FileStream fileStream = null; StreamWriter streamWriter = null; try {string path = Path. combine (System. appDomain. currentDomain. setupInformation. applicationBase, string. Format ("{0: yyyyMMdd}", DateTime. now); using (fileStream = new FileStream (path, FileMode. append, FileAccess. write) {using (streamWriter = new StreamWriter (fileStream) {streamWriter. write (content); if (streamWriter! = Null) {streamWriter. Close () ;}} if (fileStream! = Null) {fileStream. Close () ;}} catch {}}}
So called in Service1,
Public partial class Service1: ServiceBase {System. threading. timer recordTimer; public Service1 () {InitializeComponent ();} protected override void OnStart (string [] args) {reply ();} protected override void OnStop () {if (recordTimer! = Null) {recordTimer. dispose () ;}} private void IntialSaveRecord () {TimerCallback timerCallback = new TimerCallback (CallbackTask); AutoResetEvent autoEvent = new AutoResetEvent (false); recordTimer = new System. threading. timer (timerCallback, autoEvent, 10000,600 00*10);} private void CallbackTask (Object stateInfo) {FileOpetation. saveRecord (string. format (@ "current record time: {0}, status: The program runs normally! ", DateTime. Now ));}}
In this way, the service is almost written. Next, add an installation class for installation.
, Right-click service1 and choose "add installer,
650) this. width = 650; "src =" http://www.bkjia.com/uploads/allimg/131228/1556213F6-3.jpg "title =" windowsservice 04.jpg "/>
, Add an installer,
650) this. width = 650; "src =" http://www.bkjia.com/uploads/allimg/131228/15562114R-4.jpg "title =" windowsservice 05.jpg "/>
, After adding,
650) this. width = 650; "src =" http://www.bkjia.com/uploads/allimg/131228/155621L19-5.jpg "title =" windowsservice 06.jpg "/>
Set the relevant attributes and set the attributes for serviceInstaller1, mainly the description information .,
650) this. width = 650; "src =" http://www.bkjia.com/uploads/allimg/131228/1556214355-6.jpg "title =" windowsservice 07.jpg "/>
Set serviceProcessInstaller1, mainly account. Generally, select localsystem ,,
650) this. width = 650; "src =" http://www.bkjia.com/uploads/allimg/131228/155621M38-7.jpg "title =" windowsservice 08.jpg "/>
The service has been written. So how to add it to the windows service. In addition to the previous example, installutil.exe and the service exe files are manually added. These can be implemented using code. Of course, the main process is the same. Code implementation is also completed using the DOS command.
Ii. Install the Windows service using code
The Service written above generates an exe file .,
650) this. width = 650; "src =" http://www.bkjia.com/uploads/allimg/131228/1556213Q8-8.jpg "title =" Windows Service 09.jpg "/>
This exe path is required for installation. For convenience, copy the generated exe file to the running directory of the installation program.
Installation code,
Class Program {static void Main (string [] args) {Application. enableVisualStyles (); Application. setCompatibleTextRenderingDefault (false); string sysDisk = System. environment. systemDirectory. substring (0, 3); string dotNetPath = sysDisk + @ "WINDOWS \ Microsoft. NET \ Framework \ v4.0.30319 \ InstallUtil.exe "; // because the current environment is 4.0, string serviceEXEPath = Application. startupPath + @ "\ MyFirstWindowsService.exe"; // set the Service's exe The program is copied to the current running directory, so use this path string serviceInstallCommand = string. format (@ "{0} {1}", dotNetPath, serviceEXEPath); // The doscommand string serviceUninstallCommand = string used during service installation. format (@ "{0}-U {1}", dotNetPath, serviceEXEPath); // doscommand try {if (File. exists (dotNetPath) {string [] cmd = new string [] {serviceUninstallCommand}; string ss = Cmd (cmd); CloseProcess ("cmd.exe ");}} catch {} Thread. sleep (1000 ); Try {if (File. exists (dotNetPath) {string [] cmd = new string [] {serviceInstallCommand}; string ss = Cmd (cmd); CloseProcess ("cmd.exe ");}} catch {} try {Thread. sleep (3000); ServiceController SC = new ServiceController ("MyFirstWindowsService"); if (SC! = Null & (SC. status. equals (ServiceControllerStatus. stopped) | (SC. status. equals (ServiceControllerStatus. stopPending) {SC. start ();} SC. refresh ();} catch {}}/// <summary> /// run the CMD command // </summary> /// <param name = "cmd"> command </param>/ // <returns> </returns> public static string Cmd (string [] cmd) {Process p = new Process (); p. startInfo. fileName = "cmd.exe"; p. startInfo. useShellExecute = false; P. startInfo. redirectStandardInput = true; p. startInfo. redirectStandardOutput = true; p. startInfo. redirectStandardError = true; p. startInfo. createNoWindow = true; p. start (); p. standardInput. autoFlush = true; for (int I = 0; I <cmd. length; I ++) {p. standardInput. writeLine (cmd [I]. toString ();} p. standardInput. writeLine ("exit"); string strRst = p. standardOutput. readToEnd (); p. waitForExit (); p. clos E (); return strRst ;} /// <summary> /// close the process /// </summary> /// <param name = "ProcName"> process name </param> /// <returns> </returns> public static bool CloseProcess (string ProcName) {bool result = false; System. collections. arrayList procList = new System. collections. arrayList (); string tempName = ""; int begpos; int endpos; foreach (System. diagnostics. process thisProc in System. diagnostics. process. getProc Esses () {tempName = thisProc. toString (); begpos = tempName. indexOf ("(") + 1; endpos = tempName. indexOf (")"); tempName = tempName. substring (begpos, endpos-begpos); procList. add (tempName); if (tempName = ProcName) {if (! ThisProc. CloseMainWindow () thisProc. Kill (); // forcibly terminate the process result = true when the window close command is invalid;} return result ;}}
This code can actually be stored somewhere in the project or executed separately, so you have to set the dotNetPath and serviceEXEPath paths.
After running ,,
650) this. width = 650; "src =" http://www.bkjia.com/uploads/allimg/131228/1556211445-9.jpg "title =" installation completed .jpg "/>
View the recorded files in the installation directory,
650) this. width = 650; "src =" http://www.bkjia.com/uploads/allimg/131228/15562162Q-10.jpg "title =" file .jpg "/>
In this way, a windows service is successfully installed.
Code download: http://download.csdn.net/detail/yysyangyangyangshan/6032671
This article is from the "northwest poplar" blog. For more information, contact the author!