Click here to Skip to main content
15,860,844 members
Articles / Desktop Programming / Windows Forms

Alternative way for Window services to interact with desktop where operating > XP

Rate me:
Please Sign up or sign in to vote.
4.88/5 (15 votes)
23 Sep 2010CPOL3 min read 113.8K   4.4K   40   22
Alternative way for Window services to interact with desktop where operating > XP

Windows services when interacting with Desktop works fine in XP but when we change the application to Vista or greater than XP, it does not work as we expect.

Problem

When we migrate the solution to Windows 7 operating system, it runs in session 0. So you get a message:

blocked by Interactive Service Dialog Detection

This article can be one solution for the above problem.

Question

1) Why do I want the Windows service to interact with Desktop, it's not what they are made for?

Answer: Yes, Exactly! the Windows services are not make to interact with Desktop. But after introducing WCF services which can be hosted in Windows services, we may have the requirement to run the EXE file from the WCF services.

But before going through this article, please read:

Note

Before implementing this solution, please be aware of your requirements and handle all the security problems.

Introduction

Windows Services

Microsoft Windows services, formerly known as NT services, enables you to create long-running executable applications that run in their own Windows sessions. These services can be automatically started when the computer boots, can be paused and restarted, and do not show any user interface. These features make services ideal for use on a server or whenever you need long-running functionality that does not interfere with other users who are working on the same computer. You can also run services in the security context of a specific user account that is different from the logged-on user or the default computer account. For more information about services and Windows sessions:

Step 1
  • Open Visual Studio 2010
  • File -> New -> Project ->
  • Template VisualC# -> Windows
  • Project -> Windows Service
  • Name : InteractDesktopDemo
  • Ok ß

1.jpg

Step 2

Open Service1.cs, right Click in designer mode and Select AddInstaller .

Set the Properties of the installers, by default we get:

  1. serviceProcessInstaller
  2. serviceInstaller1

Go to Solution Explorer project.

Installer.designer.cs

Add the following code:

C#
private void InitializeComponent()
{
      this.serviceProcessInstaller1 = new System.ServiceProcess.ServiceProcessInstaller();
      this.serviceInstaller1 = new System.ServiceProcess.ServiceInstaller();
     //
      // serviceProcessInstaller1
     if (System.Environment.OSVersion.Version.Major <= 5)
     this.serviceProcessInstaller1.Account =
		System.ServiceProcess.ServiceAccount.LocalSystem;
     this.serviceProcessInstaller1.Password = null;
     this.serviceProcessInstaller1.Username = null;
     //
    // serviceInstaller1
    //
    this.serviceInstaller1.ServiceName = "Service1";
    //
    // ProjectInstaller
    //
   this.Installers.AddRange(new System.Configuration.Install.Installer[] {
   this.serviceProcessInstaller1,
   this.serviceInstaller1});
}

Explanation

It will check for operating system version and if the operating system is greater than Windows XP, then it will ask for username and password and after entering the credentials, the service runs under that system account. If its XP or lesser than XP, the Windows service will run under local system account.

Step 3

Add an installer

Go to Solution Explorer, right click add new item Installer.cs:

2.jpg

And add the following code:

C#
protected override void OnCommitted(IDictionary savedState)
     {
      base.OnCommitted(savedState);
     try
        {
         ServiceController nService = new ServiceController("Service1");
         nService.Start();
         }
    catch (Exception ie)
      {
       StreamWriter sw;
       sw = File.AppendText("C:\\sashidhar.txt");
       sw.WriteLine(ie.Message);
       sw.Close();
      }
     }

Explanation

The above code handles the oncommitted event which fires after the installation of the EXE file/Windows service. It helps the service to start automatically after installation.

Step 4

Add reference to Microsoft.Win32.TaskScheduler which is useful to create the task scheduler.

DLL can be found at http://taskscheduler.codeplex.com/.

C#
protected override void OnStart(string[] args)
     {
       try
        {
          if (System.Environment.OSVersion.Version.Major > 5)
            {
              //New Functionality
              // Get the service on the local machine
              TaskService ts = new TaskService();
              // Create a new task definition and assign properties
             TaskDefinition td = ts.NewTask();
             td.Principal.RunLevel = TaskRunLevel.Highest;
             td.RegistrationInfo.Description = "Does something";
            // Create a trigger that will fire the task when you are creating a new one 
            // or changing the task
             td.Triggers.Add(new RegistrationTrigger { Delay = TimeSpan.FromSeconds(1) });
            // Create an action that will launch Notepad whenever the trigger fires
            td.Actions.Add(new ExecAction("notepad"));
            // Register the task in the root folder
           ts.RootFolder.RegisterTaskDefinition(@"ssd", td);
        }
        else
        {
          //For Xp the Windows Service to interact with Desktop
          ServiceDesktopPermission();
         System.Diagnostics.Process.Start("notepad.exe");
        }
     }
     catch (Exception ie)
      {
       StreamWriter sw;
       sw = File.AppendText("C:\\Sashidhar.txt");
       sw.WriteLine(ie.Message);
       sw.Close();
      }
 }

Explanation

The above code behaves differently depending on the operating system, for operating system lesser than XP or XP. Windows Service will run in the localsystem account and interacting with desktop is checked. While in windows 7, it creates a task in the task scheduller and the task scheduler interacts with desktop. Make sure you run the Windows service in administrator account or the account which has the right to run the task in the task scheduler.

C#
static public void ServiceDesktopPermission()
    {
       try
        {
            ConnectionOptions coOptions = new ConnectionOptions();
            coOptions.Impersonation = ImpersonationLevel.Impersonate;
            // CIMV2 is a namespace that contains all of the core OS and hardware classes.
            // CIM (Common Information Model) which is an industry standard for describing
            // data about applications and devices so that administrators and software
            // management programs can control applications and devices on different
           // platforms in the same way, ensuring interoperability across a network.
           ManagementScope mgmtScope = new ManagementScope(@"root\CIMV2", coOptions);
           mgmtScope.Connect();
           ManagementObject wmiService;
           wmiService = new ManagementObject("Win32_Service.Name='" + "Service1" + "'");
           ManagementBaseObject InParam = wmiService.GetMethodParameters("Change");
           InParam["DesktopInteract"] = true;
           wmiService.InvokeMethod("Change", InParam, null);
          }
         catch (Exception ex)
          {
             //TODO: Log this error
              StreamWriter sw;
             sw = File.AppendText("C:\\Sashidhar.txt");
             sw.WriteLine("Trying to open Service");
              sw.Close();
          }
     }

Explanation

For making the Windows service interact with desktop for operating system Windows XP or lesser.

Installing

Open Visual Studio command prompt and type:

installutil <Path of the exe File>

When installing, provide the administrator credentials as shown below:

sd.jpg

Uninstalling

Open Visual studio command prompt and type:

installutil/u <Path of the exe File>

References

To be continued! Working with WCF services and WindowServices!

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionOpen file Pin
Member 100143917-Sep-15 20:40
Member 100143917-Sep-15 20:40 
QuestionIs this code available in java to interact with the desktop in windows7 Pin
Member 1110034822-Sep-14 1:58
Member 1110034822-Sep-14 1:58 
QuestionIs it possible to get the HWND of NotePad.exe in service? Under Windows7 Pin
mbtt29-Nov-12 1:45
mbtt29-Nov-12 1:45 
Questioninstallation failing Pin
RAHUL7775825-Jun-12 11:03
RAHUL7775825-Jun-12 11:03 
AnswerRe: installation failing Pin
sashidhar25-Jun-12 18:59
sashidhar25-Jun-12 18:59 
GeneralRe: installation failing Pin
RAHUL7775810-Jul-12 9:15
RAHUL7775810-Jul-12 9:15 
GeneralRe: installation failing Pin
Michael Haephrati10-Jun-13 10:40
professionalMichael Haephrati10-Jun-13 10:40 
GeneralMy vote of 5 Pin
sharp prospector21-Sep-10 3:03
sharp prospector21-Sep-10 3:03 
GeneralRe: My vote of 5 Pin
sashidhar21-Sep-10 4:18
sashidhar21-Sep-10 4:18 
GeneralMy vote of 1 Pin
WillemSe20-Sep-10 20:50
WillemSe20-Sep-10 20:50 
GeneralRe: My vote of 1 Pin
sashidhar21-Sep-10 0:05
sashidhar21-Sep-10 0:05 
GeneralStill not convinced it's needed. Pin
PIEBALDconsult18-Sep-10 3:11
mvePIEBALDconsult18-Sep-10 3:11 
GeneralRe: Still not convinced it's needed. Pin
sashidhar18-Sep-10 5:22
sashidhar18-Sep-10 5:22 
GeneralRe: Still not convinced it's needed. Pin
John Brett19-Sep-10 23:30
John Brett19-Sep-10 23:30 
GeneralRe: Still not convinced it's needed. Pin
sashidhar19-Sep-10 23:52
sashidhar19-Sep-10 23:52 
GeneralRe: Still not convinced it's needed. Pin
John Brett19-Sep-10 23:58
John Brett19-Sep-10 23:58 
GeneralRe: Still not convinced it's needed. Pin
sashidhar20-Sep-10 0:27
sashidhar20-Sep-10 0:27 
GeneralRe: Still not convinced it's needed. Pin
pzand23-Sep-10 15:14
pzand23-Sep-10 15:14 
GeneralRe: Still not convinced it's needed. Pin
sashidhar23-Sep-10 18:55
sashidhar23-Sep-10 18:55 
GeneralNice Article..! Pin
CoderOnline17-Sep-10 18:12
CoderOnline17-Sep-10 18:12 
GeneralRe: Nice Article..! Pin
sashidhar17-Sep-10 20:32
sashidhar17-Sep-10 20:32 
GeneralRe: Nice Article..! Pin
Member 464497017-Sep-10 22:23
Member 464497017-Sep-10 22:23 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.