Several ways to set up a C#windows service description and allow services to interact with the desktop (author blogs and a whole bunch of C # creation services articles)

Source: Internet
Author: User

Method One:

Rewrite the install (), Uninstall () method in ProjectInstaller.cs


public override void Install (IDictionary stateserver)
{
Microsoft.Win32.RegistryKey system,
Hkey_local_machine/services/currentcontrolset
CurrentControlSet,
.../services
Services
.../<service name>
Service
.../parameters-this is where can put service-specific configuration
Config

Try
{
Let the project installer does its job
Base. Install (StateServer);

Open the Hkey_local_machine/system key
System = Microsoft.Win32.Registry.LocalMachine.OpenSubKey ("system");
Open CurrentControlSet
CurrentControlSet = System. OpenSubKey ("CurrentControlSet");
Go to the Services key
Services = Currentcontrolset.opensubkey ("services");
Open the key for your service, and allow writing
Service = Services. OpenSubKey (This.serviceInstaller1.ServiceName, true);
ADD your service ' s description as a REG_SZ value named "description"
Service. SetValue ("Description", "PI real-time data acquisition: energy--take one data at 8 or 20 points per day; Truck scale--take data at 1 points per day; Device status – data is taken once per minute. ");
(Optional) ADD Some custom information your service would use ...
Allow services to interact with the desktop
Service. SetValue ("Type", 0x00000110);
Config = service. CreateSubKey ("Parameters");
}
catch (Exception e)
{
Console.WriteLine ("An exception is thrown during service installation:/n" + e.tostring ());
}
}

public override void Uninstall (IDictionary stateserver)
{
Microsoft.Win32.RegistryKey system,
CurrentControlSet,
Services
Service

Try
{
Drill down to the service key and open it with write permission
System = Microsoft.Win32.Registry.LocalMachine.OpenSubKey ("system");
CurrentControlSet = System. OpenSubKey ("CurrentControlSet");
Services = Currentcontrolset.opensubkey ("services");
Service = Services. OpenSubKey (This.serviceInstaller1.ServiceName, true);
Delete any keys created during installation (or that your service created)
Service. Deletesubkeytree ("Parameters");
//...
}
catch (Exception e)
{
Console.WriteLine ("Exception encountered while uninstalling service:/n" + e.tostring ());
}
Finally
{
Let the project installer does its job
Base. Uninstall (StateServer);
}
}

Method Two: This method has been tested, found invalid, tick is selected, but the program started or no interface appears, as if the need for a computer restart to take effect

We write a service, sometimes to let the service start an application, we need to modify the properties of the service, tick allow service to interact with the desktop,

You can use the registry to modify the implementation, we must operate after installation, so please rewrite installer onafterinstall.

protected override void Onafterinstall (System.Collections.IDictionary savedstate) {
RegistryKey rk = registry.localmachine;
string key = @ "system/currentcontrolset/services/" + this.sInstaller.ServiceName;
RegistryKey sub = rk. OpenSubKey (key, true);
int value = (int) Sub. GetValue ("Type");
if (value < 256) {
Sub. SetValue ("Type", value | 256);
}
Base. Onafterinstall (savedstate);
Modify the registry when}onstart
[hkey_local_machine/system/currentcontrolset/services/your service name]
"Type" =dword:00000010
Key value+256
Like now, 00000010 is 16+256=272.
16 binary is 00000110 method three: Use System.ServiceProcess.ServiceController
            connectionoptions cooptions = new ConnectionOptions ();            coOptions.Impersonation = impersonationlevel.impersonate;            Managementscope mgmtscope = new System.Management.ManagementScope (@ "root/cimv2", Cooptions);             Mgmtscope.connect ();             ManagementObject wmiservice;             wmiservice = new ManagementObject ("win32_service.name=" + servicecontroller.servicename + "'");             Managementbaseobject Inparam = Wmiservice.getmethodparameters ("Change");            inparam["desktopinteract"] = true;            Managementbaseobject OutParam = WmiService.InvokeMethod (" Change ", Inparam, NULL);            Servicecontroller.start ();

Description: In your own Write a system service program, need to often use the "allow to interact with the desktop" setting, many online use to modify the form of the registry implementation, I tested, modify the registry, the selected tick is selected,

But not the application, it is said to restart the computer can be, but I do not want to restart, the actual application is not allowed to restart, so there is no test restart is feasible.

For example:

When I need to run the service program, pop up my application and then tick the Windows Service "Allow service to interact with desktop"

When I do not want to pop up the application interface, then remove the tick.

Implementation method:

1. Programmed when the service program is installed, ProjectInstaller.cs


Using System;
Using System.Collections;
Using System.Collections.Generic;
Using System.ComponentModel;
Using System.Configuration.Install;
Using System.Linq;
Using Microsoft.Win32; Be sure to reference this namespace for registry operations


Namespace Monitorservice
{
[Runinstaller (True)]
public partial class Projectinstaller:installer
{
Public ProjectInstaller ()
{
InitializeComponent ();
This. context.parameters["Servercode"]. ToString (); Read the server number entered during installation
}

private void Projectinstaller_afterinstall (object sender, Installeventargs e)
{
setting allows services to interact with the desktop
Setservicetable ("Monitorservice");
}
<summary>
Settings allow the service to interact with the desktop, modify the registry, and restart the system to take effect
</summary>
<param name= "ServiceName" > Service Program name </param>
private void Setservicetable (string ServiceName)
{
RegistryKey rk = registry.localmachine;
string key = @ "system/currentcontrolset/services/" + ServiceName;
RegistryKey sub = rk. OpenSubKey (key, true);
int value = (int) Sub. GetValue ("Type");
Sub. SetValue ("Type", value | 256);
}
}
}

2. Registry modification

Modify the registry when OnStart
[HKEY_LOCAL_MACHINE "SYSTEM" CurrentControlSet "Services" your service name]
"Type" =dword:00000010
Key value+256
Like now, 00000010 is 16+256=272.
16 Refining is 00000110

3.SC program modification to allow interaction with the desktop

At the DOS command prompt, enter:
sc config Monitorservice type= interact type= own

You can enter.

can be implemented in batch mode, save the following code as Myservice.bat:

REM Configuration service program to allow interaction with the desktop
@echo "Ready to stop the service program ..."
sc stop MyService
@echo "settings allow interaction with the desktop"
sc config MyService type= interact type= own
@echo "Restarting service ..."
SC start MyService
@echo "Start the service successfully! "

Cancel "Allow interaction with the desktop"

At the DOS command prompt, run the following statement:

sc config MyService type= own

Tested: You can select "Allow interaction with the desktop", but when you start the service, you cannot eject the application's interface.

3 can fulfill all requirements perfectly.

At this point, the problems I encountered are also perfectly resolved.

Deploy with VS2003, start the service immediately after the service is installed and select the "Allow service to interact with desktop" and add the service description method

<textarea cols= "rows=" name= "code" class= "C-sharp" >-----------start immediately--------------private void Serviceinstaller1_afterinstall (object sender, System.Configuration.Install.InstallEventArgs e) {ServiceController MyService = new ServiceController ("Xjoapigeonholeserver"); Myservice.start (); Myservice.dispose (); Add Description: 1.1 There is no direct method, 2.0 has a direct method serviceinstaller.description//----------------------------Add service description information to start------------ public override void Install (IDictionary stateserver) {Microsoft.Win32.RegistryKey system,//hkey_local_machine/ Services/currentcontrolset CurrentControlSet,//.../services Services,//.../&lt; Service name&gt; Service,//.../parameters-this is where you can put Service-specific configuration config; try {//let The project installer does its job base. Install (StateServer); Open the Hkey_local_machine/system Key system = Microsoft.Win32.Registry.LocalMachine.OpenSubKey ("system"); Open CurrentControlSet CurrentControlSet = System. OpenSubKey ("CurrentCOntrolset "); Go to the Services Key Services = Currentcontrolset.opensubkey ("services"); Open the key for your service, and allow writing service = Services. OpenSubKey (This.serviceInstaller1.ServiceName, true); ADD your service ' s description as a REG_SZ value named "description" service. SetValue ("Description", "Xjoa system automatic Archiving Service (Beijioffice)"); (Optional) ADD Some custom information your service would use ...//allow services to interact with desktop service. SetValue ("Type", 0x00000110); Config = service. CreateSubKey ("Parameters"); } catch (Exception e) {Console.WriteLine ("An Exception is thrown during service installation:/n" + e.tostring ());}} public override void Uninstall (IDictionary stateserver) {Microsoft.Win32.RegistryKey system, CurrentControlSet, services, service; try {//drill down to the service key and open it with write permission system = Microsoft.Win32.Registry.LocalMachine.Ope Nsubkey ("System"); CurrentControlSet = System. OpenSubKey ("CurrentControlSet"); Services = Currentcontrolset.opensubkey ("Services "); Service = Services. OpenSubKey (This.serviceInstaller1.ServiceName, true); Delete any keys to created during installation (or that your service created) service. Deletesubkeytree ("Parameters"); //... } catch (Exception e) {Console.WriteLine ("Exception encountered while uninstalling service:/n" + e.tostring ());} finally { Let the project installer does its job base. Uninstall (StateServer); }}//----------------------------end----------------------------</textarea>

Four, this service program runs without a graphical interface?

Yes, we saw the graphical interface when we ran the Mfc1.exe directly, but we didn't see any interface in the Service list with the start in the context menu. What's the deal?

We also need to add a parameter when using the CreateService function (Install ()) to allow the program to interact with the desktop, that is, to display the interface. This parameter is service_interactive_process.

After filling the CreateService:

  SC_HANDLE hService = ::CreateService(
     hSCM, m_szServiceName, m_szServiceName,
     SERVICE_ALL_ACCESS,
SERVICE_WIN32_OWN_PROCESS | SERVICE_INTERACTIVE_PROCESS,
     SERVICE_DEMAND_START, SERVICE_ERROR_NORMAL,
     szFilePath, NULL, NULL, _T("RPCSS"), NULL, NULL);

  After you compile the MFC1 again, uninstall the service and install the service. We can see that the original dialog box appears when you start mfc1 through the list of services.

If you want to set the service to start automatically, change the Service_demand_start to Service_Auto_Start.

http://blog.csdn.net/jiangxinyu/article/details/5397060

Several ways to set up a C#windows service description and allow services to interact with the desktop (author blogs and a whole bunch of C # creation services articles)

Related Article

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.