Search code examples
c#timerwindows-servicesbatch-processingelapsed

C# Timer Elapsed Not Running Batch Process in Windows Service


I have implemented the following code with a Timer.Elapsed event which runs a batch process and takes a screenshot of my desktop. The batch process runs perfectly everywhere else in the code except in the ElapsedHandler. I know that the handler is being called properly because I added some code to print to a file, which works perfectly. The batch process itself however, never gets executed. Am I missing something about the Timer that is causing the problem?

using System;
using System.IO;
using System.Diagnostics;
using System.Threading;
using System.Timers;
using System.Drawing;
using System.Drawing.Imaging;
using System.ServiceProcess;

namespace ScreenCaptureService
{
    public class ScreenCaptureService : ServiceBase
    {
        private const int durationInMinutes = 1;
        private System.Timers.Timer t;

        protected override void OnStart(string[] args)
        {
            t = new System.Timers.Timer((float)(1000));
            t.Elapsed += new ElapsedEventHandler(ElapsedHandler);
            t.Enabled = true;
        }

        protected void ElapsedHandler(object sender, ElapsedEventArgs e)
        {
            string testpath = @"C:\Dump\new.txt";
            if (!File.Exists(testpath))
            {
                File.CreateText(testpath);
                using (StreamWriter sw = File.AppendText(testpath))
                {
                    sw.WriteLine("Initialized");
                }
            }
            else
            {
                using (StreamWriter sw = File.AppendText(testpath))
                {
                    sw.WriteLine("Hello " + DateTime.Now.ToString());
                }
            }
            Process.Start(@"C:\users\wyoung\screenshot.bat");
        }

        protected override void OnStop()
        {
            t.Enabled = false;
        }
    }
}

Solution

  • Windows services run from a separate session with a different desktop so your service will not be able to take an screenshot of your desktop (at least not without a lot of work).

    You'll have to either run this as a scheduled task or as a program that runs on startup.