0

バッチ プロセスを実行し、デスクトップのスクリーンショットを取得する 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;
        }
    }
}
4

1 に答える 1