2009-12-02 109 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