Friday, 20 March 2015

Launch GUI Application from windows Service


Launch GUI Application from windows Service

Microsoft Windows service is a background process. Mostly, we are not implementing any GUI design in the service project. But, there is an option to implement a page and system tray functionality in the service project. Some case we need to launch our GUI Application from service project. The below step help to launch application from service

Step 1: Open Visual Studio -> File -> New -> Project

Step 2: Choose your flexible code behind template in the dialog window. I’m choosing C# template

Step 3: Select Windows -> Select “Windows Service” project template

Step 4: Rename your Project name “ServiceIntractGUIApplication” Then select Ok button. By default, Service1.cs file will be create in your project


Step 5: Add reference Microsoft.Win32.TaskScheduler to the service project for task scheduler. Implement below code in your “onStart” methods. Here. I try to launch calculator application when the service start
/// <summary>
        /// Executes when a Start command tigger from service controller
        /// </summary>
        /// <param name="args"></param>
        protected override void OnStart(string[] args)
        {
            try
            {              
                if (System.Environment.OSVersion.Version.Major > 5)
                {
                    // Initialize task service for access to the Task Scheduler service for managing registered tasks
                    TaskService taskService = new TaskService();

                    // Create a new task definition for initializing all the components of a task, like settings, triggers, actions, and registration information.
                    TaskDefinition taskDefinition = taskService.NewTask();

                    //Assing the task run level information
                    taskDefinition.Principal.RunLevel = TaskRunLevel.Highest;
                    taskDefinition.RegistrationInfo.Description = "Sample service run the GUI Application ";

                    // Create a trigger for executing your task with delay time
                    taskDefinition.Triggers.Add(new RegistrationTrigger { Delay = TimeSpan.FromSeconds(1) });

                    // Initialize task action,Which will launch the application when the trigger fires
                    taskDefinition.Actions.Add(new ExecAction(@"calc.exe"));

                    // Registers (creates) a task in a specified location
                    taskService.RootFolder.RegisterTaskDefinition(@"ssd", taskDefinition);
                }
                else
                {
                    //Should be enable DesktopInteract option in our service for XP OS
                    EnableGUIInteractPermission();
                    System.Diagnostics.Process.Start(@"calc.exe");
                }
            }
            catch (Exception ex)
            {
                LogException(ex);
            }
        }

/// <summary>
        /// Enbale GUI interact permission in the service property
        /// </summary>
        private void EnableGUIInteractPermission()
        {
            try
            {
                ConnectionOptions coOptions = new ConnectionOptions();
                coOptions.Impersonation = ImpersonationLevel.Impersonate;
                ManagementScope mgmtScope = new ManagementScope(@"root\CIMV2", coOptions);
                mgmtScope.Connect();
                ManagementObject wmiService;
                wmiService = new ManagementObject("Win32_Service.Name='" + "SampleService" + "'");
                ManagementBaseObject InParam = wmiService.GetMethodParameters("Change");
                InParam["DesktopInteract"] = true;

                wmiService.InvokeMethod("Change", InParam, null);
            }
            catch (Exception ex)
            {
                LogException(ex);
            }
        }

        /// <summary>
        /// Log exception details
        /// </summary>
        /// <param name="ex">The exception object</param>
        private void LogException(Exception ex)
        {
            using (var fileStream = File.Open("C:\\ErrorLog.txt", FileMode.OpenOrCreate))
            {
                var content = ASCIIEncoding.ASCII.GetBytes(ex.Message);
                fileStream.Write(content, 0, content.Count());
                fileStream.Close();
            }
        }
Step 6: Add Installer class for defining service setting.
Right Click your project ->Add -> New Item -> Select “Installer Class”. Implement below code in your installer class constructor “SampleServiceInstaller” , Here we should use service account as a user then implement account information like username and password
[RunInstaller(true)]
    public partial class SampleServiceInstaller : System.Configuration.Install.Installer
    {
        public SampleServiceInstaller()
        {
            InitializeComponent();
            ServiceProcessInstaller serviceProcessInstaller =
                             new ServiceProcessInstaller();
            ServiceInstaller serviceInstaller = new ServiceInstaller();

            //# Service Account Information
            // Use service account should be user type for interact with GUI Application
            serviceProcessInstaller.Account = ServiceAccount.User;
            serviceProcessInstaller.Username = @"userName";
            serviceProcessInstaller.Password = "password";

            // Define service display name for your understand
            serviceInstaller.DisplayName = "SampleService";

            // Define service start type
            serviceInstaller.StartType = ServiceStartMode.Automatic;

            // Define service name
            serviceInstaller.ServiceName = "SampleService";

            this.Installers.Add(serviceProcessInstaller);
            this.Installers.Add(serviceInstaller);
        }
    }
Now, Right click on Command prompt (cmd.exe) then select “Run as Administrator”. Now, use below for installing service
C:\Windows\Microsoft.NET\Framework\v4.0.30319>InstallUtil.exe /i "C:\ServiceIntractGUIApplication\bin\Debug\ServiceIntractGUIApplication.exe"
Refer the below message for confirmation about your installation status
The Commit phase completed successfully.
The transacted install has completed.
For Uninstall use below command
C:\Windows\Microsoft.NET\Framework\v4.0.30319>InstallUtil.exe /u "C:\ServiceIntractGUIApplication\bin\Debug\ServiceIntractGUIApplication.exe"

Step 7: Click Start, click in the Start Search box, type services.msc , and then press enter. Here, listing all the service of the system. Select your service and right click then start.

Now Calculator application will be open.

1 comment: