Several Methods to register a program as a service

Source: Internet
Author: User
Tags net command
Method 1: Use the inf file
Note: ** The Error message "Error 1053: the service did not respond to The start or control request in a timely fashion." is displayed when the registered service cannot be started .), unable to find the cause, give up **:

Add a service:
[Version]
Signature = "$ windows nt $"
[Defainstall install. Services]
AddService = myTest, My_AddService_Name
[My_AddService_Name]
DisplayName = myTest
Description = myTest service.
ServiceType = 0x10
StartType = 2
ErrorControl = 0
Servicebinary1_111_mytest.exe

Save as inetsvr. inf and register the file in the running state:
Rundll32.exe setupapi, InstallHinfSection DefaultInstall 128 c: \ path \ myTestRegister. inf
In this example, add a service named myTest.

//////////////////
Notes:
1. The last four items are
Service type: 0x10 is an independent process service, and 0x20 is a shared process service (such as svchost );
Startup Type: 0 system boot loading, 1 OS initialization loading, 2 SCM (Service Control Manager) automatic start, 3 manual start, 4 disabled.
(Note: 0 and 1 can only be used for drivers)
Error Control: 0 ignore, 1 continue and warn, 2 switch to lastknowngood settings, 3 blue screen.
Service Program location: % 11% indicates the System32 directory, % 10% indicates the system directory (winnt or Windows), and % 12% indicates the drive directory system32drivers.
For other values, see DDK. You can also directly use the full path without variables.
These four items are mandatory.

2. In addition to the six projects in the example, there are loadordergroup and dependencies. Not commonly used.
3. inetsvr is followed by two commas, because an uncommon parameter flags is omitted in the middle.

Delete A service:
[Version]
Signature = "$ Windows NT $"
[Defainstall install. Services]
Delservice = inetsvr

It's easy, isn't it?
You can also import the registry. However, INF has its own advantages.

1. Export a registry key that comes with the system service. You will find that the execution path is as follows:
"ImagePath" = hex (2): 25, 00, 53,00, 79,00, 00, 6d, 00, 6f, 00, 6f, 00,
, 00, 5C, 79, 00, 00, 6d, 00, 00, 5C,
00, 6c, 00, 6e, 00, 00, 00, 00
Poor readability. In fact, it is % SystemRoot % system32 lntsvr.exe, but the data type is REG_EXPAND_SZ. When you manually import the Registry
It is obviously inconvenient to define ImagePath when adding a service. The use of the inf file does not solve this problem at all, ServiceBinary (that is, ImagePath)
Automatically becomes REG_EXPAND_SZ.

2. The most important thing is that, like using SC and other tools, the effect of the inf file is immediate, and the file must be restarted after the reg is imported.
3. The inf file automatically adds a Security sub-key for the Registry Key of the Service to make it look more like the built-in service of the system.
In addition, AddService, DelService, AddReg, and DelReg can be used simultaneously and repeatedly. That is, multiple services and registry keys can be added and deleted at the same time.

 

Certificate --------------------------------------------------------------------------------------------------------------------------------------

Method 2: Use cnames to call mytest.exe to generate a service
Note: ** this method has been successfully tested. You can start or stop the service (but you cannot see the run interface of the exe :()**

(1) first use C # to create a "Window service" project myTestService,
Drag two controls on the WatchFile. cs interface: fileSystemWatcher1 and eventLog1,
Set the attributes of fileSystemWatcher to "myTest.exe" and path( mymymytest.exe ),
Set source of eventLog1 to fileSystemWatcher1;

Click "add installer" in the Properties window ",
A new page, ProjectInstaller. cs, is created. Set the account attribute of serviceProcessInstaller1 on this page to LocalSystem. serviceInstaller1 settings are related to services. For example, if StartType is set to Automatic operation,
DisplayName myTestService1 is the name of the generated service...

(2) Compile the WatchFile. cs Program (see later)

(3) Build a mytestservice.exe file under the bin \ debugof the project.
In the. NET command prompt, enter the bin \ debug of the project,
Installation Service: installutil myTestService.exe
Uninstall service: install/u myTestService.exe (stop the service before unloading)

You can also create an installation file:
Add an installation project TestSetup,
Right click: Add-> project output (select main output ),
Right-click View> Custom Action (right-click here)> application folder> Add
Build this project. There will be an installation file in the Debug directory of the TestSetup folder.

(4) After the installation, you can see that the Service myTestService1 already exists in the service on the control panel,
You can start and stop the test to see if the exe is not started (in the process), or view the computer application log file to view the print information in the program.

 

The main program is as follows:
//////////////////
WatchFile. cs program: Mainly OnStart and OnStop

======= OnStart start service ========
Protected override void OnStart (string [] args)
{
Try
{
EventLog1.WriteEntry ("[myTest Info]: Start begin! "); // Recorded in the Application Log
Process [] testService_processNames = Process. GetProcessesByName (System. Diagnostics. Process. GetCurrentProcess (). ProcessName );
System. Diagnostics. Process [] test_processNames = System. Diagnostics. Process. GetProcessesByName ("myTest ");

// If there is more than one process
If (testService_processNames.Length> 1 | test_processNames.Length> 0)
{
EventLog1.WriteEntry ("[myTest Info]: myTest is already running ");
Return;
}
Else
{
// Define filepath and filename in App. config
System. Diagnostics. ProcessStartInfo Info = new System. Diagnostics. ProcessStartInfo ();
Info. WorkingDirectory = System. Configuration. ConfigurationSettings. Maid. Get ("filepath"); // path of exe
Info. FileName = System. Configuration. ConfigurationSettings. receivettings. Get ("filename"); // name of exe
// Info. Arguments = "";

// Info. CreateNoWindow = false;
// Info. Verb = "open ";
Info. WindowStyle = System. Diagnostics. ProcessWindowStyle. Normal;
// Info. UseShellExecute = true;

// Declare a program class
System. Diagnostics. Process proc;

Try
{
Proc = system. Diagnostics. process. Start (Info); // start the external program mytest.exe
}
Catch (system. componentmodel. win32exception E)
{
Eventlog1.writeentry ("[mytest info]: The system cannot find the specified program file. \ R {0} "+ E. Message );
Return;
}

//// Print the start time of the external program
Eventlog1.writeentry ("Start Time of the external program: {0}", Proc. starttime );

//
//// Wait 3 seconds
// Proc. waitforexit (3000 );
//
/// Forcibly terminate an external program if it has not ended
// If (Proc. HasExited = false)
//{
// EventLog1.WriteEntry ("the external program is forcibly terminated by the main program! ");
// Proc. Kill ();
//}
// Else
//{
// EventLog1.WriteEntry ("the external program Exits normally! ");
//}
// EventLog1.WriteEntry ("End Time of the external program: {0}", Proc. ExitTime );
// EventLog1.WriteEntry ("returned value when an external program stops running: {0}", Proc. ExitCode );

}

}
Catch (System. Exception ex)
{
EventLog1.WriteEntry ("[myTest Info]: Start error-" + ex. Message );
Return;
}

}

 

======= OnStop stop service ========
Protected override void OnStop ()
{
Try
{
EventLog1.WriteEntry ("[myTest Info]: Stop Begin! ");
System. Diagnostics. Process [] Test_processNames = System. Diagnostics. Process. GetProcessesByName ("myTest ");
Foreach (System. Diagnostics. Process processChild in Test_processNames)
{
EventLog1.WriteEntry ("[PBX Info]: ProcessName =" + processChild. ProcessName );
ProcessChild. Kill ();
}
}
Catch (System. Exception ex)
{
Eventlog1.writeentry ("[mytest info]: STOP error-" + ex. Message );
Return;
}
}

 

======= Write a TXT Log File ========

Public static void writelog (string strlog)
{
String strpath;
Strpath = "D: \ test ";
Strpath + = @ "\ mylog. TX;
Filestream FS = new filestream (strpath, filemode. openorcreate, fileaccess. Write );
Streamwriter m_streamwriter = new streamwriter (FS );
M_streamwriter.basestream.seek (0, seekorigin. End );
M_streamWriter.WriteLine (strLog );
M_streamWriter.Flush ();
M_streamWriter.Close ();
Fs. Close ();
}

========= App. config ==========

<? Xml version = "1.0" encoding = "UTF-8"?>
<Configuration>
<Deleetask>
<Add key = "filepath" value = "D: \ myfile \ done"/>
<Add key = "filename" value = "myTest.exe"/>
</AppSettings>
</Configuration>

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.