2009-12-02 50 views
4

我必须每隔一秒捕获一次桌面屏幕截图。在Winform应用程序中运行正常。但在将代码移到Windows Service后,它不捕获屏幕截图。任何想法为什么它不这样做?C#:从Windows服务捕获屏幕

这里是代码

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"); 
     } 
} 
+0

另请参阅http://stackoverflow.com/questions/1002064/screen-capture-from-windows-service – rogerdpack 2012-09-26 16:24:17

+0

另请参阅http://stackoverflow.com/questions/5200341/capture-screen-on-server-desktop -session/12851218 – Theraot 2013-03-24 07:39:35

回答

8

你有“允许服务与桌面交互”检查(在服务属性)?

+2

在Windows XP上我知道这是解决方案,但我不知道它是否与Windows签证/ 7 – Peter 2009-12-02 11:40:02

+0

谢谢。这个选项没有被选中。我如何使用代码检查它。 – Mohsan 2009-12-02 11:42:49

+3

Petoj是正确的。这将在XP上运行,但Vista/7不会允许这样做。 – MutantNinjaCodeMonkey 2011-08-26 08:06:09