Search This Blog

Windows service Interact with Desktop- Display GUI

using System;
using System.Collections;
using System.ComponentModel;
using System.Configuration.Install;
using System.ServiceProcess;
using Microsoft.Win32;
using System.Management;


using System.Diagnostics;
namespace Service1
{
///
/// Summary description for ProjectInstaller.
///

[RunInstaller(true)]
public class ProjectInstaller : System.Configuration.Install.Installer
{
///
/// Required designer variable.
///

private System.ComponentModel.Container components = null;
private string SerName = "service1";
public ProjectInstaller()
{
// This call is required by the Designer.
InitializeComponent();

// TODO: Add any initialization after the InitComponent call





ServiceInstaller si = new ServiceInstaller();
si.ServiceName = SerName;
si.DisplayName = SerName;
si.Description = "services1";
si.AfterInstall += new InstallEventHandler(si_AfterInstall);



si.StartType = ServiceStartMode.Manual;
Installers.Add(si);
ServiceProcessInstaller spi = new ServiceProcessInstaller();
spi.Account = System.ServiceProcess.ServiceAccount.LocalSystem;


spi.Password = null;
spi.Username = null;
Installers.Add(spi);

}

#region Component Designer generated code
///
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
///

private void InitializeComponent()
{
//
// ProjectInstaller
//
this.AfterInstall += new System.Configuration.Install.InstallEventHandler(this.ProjectInstaller_AfterInstall);

}
#endregion

private void si_AfterInstall(object sender, System.Configuration.Install.InstallEventArgs e)
{
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='" + SerName + "'");
ManagementBaseObject InParam = wmiService.GetMethodParameters("Change");
InParam["DesktopInteract"] = true; ManagementBaseObject OutParam = wmiService.InvokeMethod("Change", InParam, null);
}





}
}

Stop Windows Service -C# code

. System.ServiceProcess.ServiceController sc = new System.ServiceProcess.ServiceController();
sc.ServiceName = "ServiceName";
if (sc.Status == System.ServiceProcess.ServiceControllerStatus.Running)
{
sc.Stop();
}

Start Windows Service -C# code

ServiceController sc = new ServiceController();
sc.ServiceName = "ServiceName1";
if (sc.Status == ServiceControllerStatus.Stopped)
{
sc.Start();
}