Typically, services are designed to run unattended without any UI with any need to interact with desktop or any GUI application. However, in some cases, it is desired to let the service show and communicate with graphical applications. A reason might be to track an already developed application and start this app if closed. Or you might want some input from the user or want to alert him immediately about something serious that has happened. Whatever the reason be, there is always a need to find a way to enable your service to display the GUI application in an interactive windows satiation.

Solution is one click away and we only need to mark the "Allow Service to interact with desktop" as checked. But the question is can we do this programmatically? If yes then how? 

There are four ways to change the windows service options and we will discuss them one by one. But before that you need to know that to make a service interact with the desktop, the service

  • Account type must be Local System.
  • Service type must be Own Process or Shared Process.

1. Through Windows Registry

A service installed on the system has its options saved in the system registry under "System\CurrentControlSet\Services"in LocalMachine key with your service name. The name/value pair we are interested in is "type". Its type is integer and it is equivalent to ServiceType in its value. Here is how we can do this.

var ServiceKeys = Microsoft.Win32.Registry                
.LocalMachine.OpenSubKey(String.Format( @"System\CurrentControlSet\Services\{0}", ServiceName), true);
            
try
   {
      var ServiceType = (ServiceType)(int)(ServiceKeys.GetValue("type"));
 
      //Service must be of type Own Process or Share Process
     if (((ServiceType & ServiceType.Win32OwnProcess) !=                                               ServiceType.Win32OwnProcess)
          && ((ServiceType & ServiceType.Win32ShareProcess) !=                                       ServiceType.Win32ShareProcess))
       {
        throw new Exception("ServiceType must be either Own Process or Shared   Process to enable interact with desktop");
       }
 
      var AccountType = ServiceKeys.GetValue("ObjectName");
      //Account Type must be Local System
      if (String.Equals(AccountType, "LocalSystem") == false)
         throw new Exception("Service account must be local system to enable interact with desktop");
      //ORing the InteractiveProcess with the existing service type
      ServiceType newType = ServiceType | ServiceType.InteractiveProcess;
                ServiceKeys.SetValue("type", (int)newType);
    }
    finally
    {
      ServiceKeys.Close();
 }

This requires the system startup since registry change is not notified to Service Control Manager (SCM), change is visible in service property window though. It is because property window always load recent settings from the registry. 
2. Through WMI

If you do not want to play with the registry or restart seems not a good option in your case then there is another solution for you which is WMI. WMI class WIN32_Service let you play with the windows service. This class provides a method called "Change" which allows you to modify the service. You can read more about WIN32_Service here. Here is how to do the job.

//Create a Management object for your service.
            var service = new System.Management.ManagementObject(
                String.Format("WIN32_Service.Name='{0}'", ServiceName));
            try
            {
                var paramList = new object[11];
                paramList[5] = true;//We only need to set DesktopInteract parameter
                var output = (int)service.InvokeMethod("Change", paramList);
                //if zero is returned then it means change is done.
                if (output != 0)
                    throw new Exception(string.Format("FAILED with code {0}", output));
 
            }
            finally
            {
                service.Dispose();
            }

Good thing in this technique is it does not require any system reboot. Only a service restart is required.

3. Through Command

SC is a command-line utility for managing services. SC is available for scripting and script can be run through .net. It means we can use sc command to configure the windows service. You can see a complete list here to unleash the power of this command. For now our purpose is to enable the "Interact with desktop" option and config command is there to do this job. What we need to do is run the command through code and if output is "[SC] ChangeServiceConfig SUCCESSS" then it means our job is done. Here is how to do this

string command = String.Format("sc config {0} type= own type= interact", ServiceName);
var processInfo = new System.Diagnostics.ProcessStartInfo()
  {
    //Shell Command
    FileName = "cmd" 
    ,
    //pass command as argument./c means carries 
    //out the task and then terminate the shell command
    Arguments = "/c" + command 
    ,
   //To redirect The Shell command output to process stanadrd output
   RedirectStandardOutput = true 
   ,
  // Now Need to create command window. 
  //Also we want to mimic this call as normal .net call
  UseShellExecute = false 
  ,
  // Do not show command window
  CreateNoWindow = true                 
                
};
 
 var process = System.Diagnostics.Process.Start(processInfo);          
 
 var output = process.StandardOutput.ReadToEnd();
 if (output.Trim().EndsWith("SUCCESS") == false)
     throw new Exception(output); 
4. Through interop

Question is, do we need this when we have three nice options using managed code. For me it is useless and that's why I am leaving it

Let me end this article with words of caution.

The "Interact with Desktop" option is not supported by Microsoft in Windows Vista and newer. So use it wisely and redesign your app if there is a solid chance that your service can be installed on Vista or Server 2008.

Link:http://www.c-sharpcorner.com/uploadfile/Yousafi/allow-windows-service-to-interact-with-desktop/

Allow windows service to "Interact with desktop"的更多相关文章

  1. Installing Jenkins as a Windows service

    Install Jenkins as a Windows service NOTE: if you installed Jenkins using the windows installer, you ...

  2. C#创建、安装、卸载、调试Windows Service(Windows 服务)的简单教程

    前言:Microsoft Windows 服务能够创建在它们自己的 Windows 会话中可长时间运行的可执行应用程序.这些服务可以在计算机启动时自动启动,可以暂停和重新启动而且不显示任何用户界面.这 ...

  3. C# Windows service 开发笔录

    本文将详细图解,开发Windows service的过程. 功能:数据库查询数据后,经过处理,每天定时发送邮件. 一.WinForm调试 1.新建Windows service项目 2.新建WinFo ...

  4. [转]Win7、Windows Server 2008下无法在Windows Service中打开一个已经存在的Excel 2007文件问题的解决方案

    昨天,组里一个小朋友告诉我,他写的报表生成服务中无法打开一个已经存在的Excel 2007文件,他的开发环境是Win7.Visual Studio .Net 2008(Windows Server 2 ...

  5. Windows Service的官方描述,抄下来(不写obj就是LocalSystem)

    How to create a Windows service by using Sc.exe Email Print Support for Windows XP has ended Micro ...

  6. Windows Service 学习系列(二):C# windows服务:安装、卸载、启动和停止Windows Service几种方式

    一.通过InstallUtil.exe安装.卸载.启动.停止Windows Service 方法一 1.以管理员身份运行cmd 2.安装windows服务 切换cd C:\Windows\Micros ...

  7. SyncThingWin -- Run syncthing as a windows service

    SyncThingWin Auto restart and minor bug fixes bloones released this on 23 Dec 2014 There is now an a ...

  8. How to Run Syncthing 24/7 as a Windows Service with AlwaysUp

    http://www.coretechnologies.com/products/AlwaysUp/Apps/RunSyncthingAsAWindowsService.html Automatica ...

  9. Windows Service的转换与部署

    开发Windows Service,可能会碰到以下两种情况. 1. 直接开发一个Windows Service 网上有很多教程,可以参考这个: http://www.cnblogs.com/sorex ...

随机推荐

  1. gdb 调试学习

    gdb 是unix/linux 系统下的程序调试工具,和IDE(如VS, Eclipse等)的图形化调试工具相比,gdb在断点,跟踪显示方面有着不足,但是它在某些方面比图形化调试工具更加丰富的功能. ...

  2. Linux 命令速查

    学生信,Linux是最最基本的技能,要尽量将自己的工作平台转移到Linux,编程写脚本,这样会极大的提升工作效率,找工作时也不会太怂.Linux所有的任务都是通过命令来完成的,具有高度的统一性.Lin ...

  3. Calendar类中add/set/roll方法的区别

    欢迎和大家交流技术相关问题: 邮箱: jiangxinnju@163.com 博客园地址: http://www.cnblogs.com/jiangxinnju GitHub地址: https://g ...

  4. C/C++大数库简介

    在网络安全技术领域中各种加密解密算法的软件实现上始终有一个共同的问题就是如何在普通的PC机上实现大数的运算.我们日常生活中所应用的PC机内部字长多是32位或64位,但是在各种加密解密的算法中为了达到一 ...

  5. linux笔记:linux系统安装-vmware虚拟机安装

    vmware版本:vmware8(百度云里备份了安装程序VMware_Workstation_wmb.zip) vmware软件安装过程: 1.在百度云中下载安装程序压缩包VMware_Worksta ...

  6. css读书笔记1:HTML标记和文档结构

    块级元素和行内元素:块级元素:上下堆叠,每个块级元素都独立占一行.块级元素的盒子宽度与父元素同宽.行内元素:左右堆叠,只有在空间不足的情况下才会折到下一行显示.行内元素的盒子会收缩包裹其内容,并尽可能 ...

  7. js字符串函数之substring() substr()

    substring 方法用于提取字符串中介于两个指定下标之间的字符 substring(start,end) 开始和结束的位置,从零开始的索引 参数     描述start     必需.一个非负的整 ...

  8. 《javascript高级程序设计》第五章 reference types

    第5 章 引用类型5.1 Object 类型5.2 Array 类型 5.2.1 检测数组 5.2.2 转换方法 5.2.3 栈方法 5.2.4 队列方法 5.2.5 重排序方法 5.2.6 操作方法 ...

  9. mysql 初始密码 设置

    mysql root 密碼的設置方法 shell> mysql -u root mysql mysql> SET PASSWORD FOR root@localhost=PASSWORD( ...

  10. Codeforces Round #308 (Div. 2)----C. Vanya and Scales

    C. Vanya and Scales time limit per test 1 second memory limit per test 256 megabytes input standard ...