C#:从Windows服务捕获屏幕 [英] C#: capture screen from Windows service

查看:77
本文介绍了C#:从Windows服务捕获屏幕的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须每隔一秒钟捕获一次Desktop的屏幕截图.在Winform应用程序中,它运行良好.但是将代码移至Windows Service后,它无法捕获屏幕截图.知道为什么不这样做吗?

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?

这是代码

public partial class ScreenCaptureService : 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)?

这篇关于C#:从Windows服务捕获屏幕的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆