开发者

C#: capture screen from Windows service

开发者 https://www.devze.com 2022-12-12 21:34 出处:网络
i have to capture screenshot of Desktop after every one second. in Winform application it is running fine. but after moving the code to Windows Service it is not capturing the screenshot. Any idea why

i have to capture screenshot of Desktop after every one second. in Winform application it is running fine. but after moving the code to Windows Service it is not capturing the screenshot. Any idea why it is not doing so?

here is the code

public partial class Screen开发者_StackOverflowCaptureService : ServiceBase
    {
        System.Timers.Timer timer = new System.Timers.Timer();

        public ScreenCaptureService()
        {
            InitializeComponent();            
            this.timer.Interval = 1000;
            this.timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed);

        }

        void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            CaptureScreen();
        }

        protected override void OnStart(string[] args)
        {
            if (!EventLog.SourceExists(this.ServiceName, Environment.MachineName))
            {
                EventLog.CreateEventSource(
                    new EventSourceCreationData(
                        this.ServiceName,
                        Environment.MachineName
                        )
                );
            }

            EventLog.WriteEntry(this.ServiceName, "The OnStart event has been called");
            this.timer.Enabled = true;
            CaptureScreen();
        }

        protected override void OnStop()
        {
            EventLog.WriteEntry(this.ServiceName, "The OnStop event has been called");
            this.timer.Enabled = false;
        }

        static int count = 1;
        private void CaptureScreen()
        {

            Bitmap printscreen = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height);

            Graphics graphics = Graphics.FromImage(printscreen as Image);

            graphics.CopyFromScreen(0, 0, 0, 0, printscreen.Size);

            printscreen.Save(@"C:\printscreen" + count++ + ".jpg", ImageFormat.Jpeg);

            EventLog.WriteEntry(this.ServiceName, "Screenshot Captured");
        }
}


Do you have "Allow service to interact with desktop" checked (in the service properties)?

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号