Windows 服务中的 C# 计时器已用完 运行 批处理

C# Timer Elapsed Not Running Batch Process in Windows Service

我已经使用 Timer.Elapsed 事件实现了以下代码,该事件运行批处理并截取我的桌面屏幕截图。除了 ElapsedHandler 之外,批处理在代码中的其他任何地方都可以完美运行。我知道处理程序被正确调用,因为我添加了一些代码来打印到一个文件,它工作得很好。然而,批处理本身永远不会被执行。我是否遗漏了导致问题的计时器的某些内容?

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;
        }
    }
}

Windows 服务 运行 来自 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).

您必须 运行 将其作为计划任务或 运行 启动时的程序。