Even there are lot of questions regarding this issue i couldn't find proper solution for this. I'm creating windows service to capture screen(windows 7). ( i tried this using windows application and it works properly. )
When I'm going to start the service then it says i cant start the service. When i check the windows log it mentioned following error.
Service cannot be started. System.ComponentModel.Win32Exception (0x80004005): The handle is invalid
at System.Drawing.Graphics.CopyFromScreen(Int32 sourceX, Int32 sourceY, Int32 destinationX, Int32 destinationY, Size blockRegionSize, CopyPixelOperation copyPixelOperation)
at ScreenCaptureService.ScreenCaptureService.TraceService() in d:\SourceControl\Test\Test\ScreenCapture\ScreenCaptureService\ScreenCaptureService.cs:line 63
at ScreenCaptureService.ScreenCaptureService.OnStart(String[] args) in d:\SourceControl\Test\Test\ScreenCapture\ScreenCaptureService\ScreenCaptureService.cs:line 32
at System.ServiceProcess.ServiceBase.ServiceQueuedMainCallback(Object state)
My code as below:
public partial class ScreenCaptureService : ServiceBase
{
private static Bitmap bmpScreenshot;
private static Graphics gfxScreenshot;
System.Timers.Timer timer = new System.Timers.Timer();
public ScreenCaptureService()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
TraceService();
timer.Elapsed += new ElapsedEventHandler(OnElapsedTime);
timer.Interval = 300000;
timer.Enabled = true;
}
protected override void OnStop()
{
timer.Enabled = false;
TraceService();
}
private void TraceService()
{
string fileName = "D:\\Screen\\abc.png";
bmpScreenshot = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height, PixelFormat.Format32bppArgb);
gfxScreenshot = Graphics.FromImage(bmpScreenshot);
gfxScreenshot.CopyFromScreen(Screen.PrimaryScreen.Bounds.X, Screen.PrimaryScreen.Bounds.Y, 0, 0, Screen.PrimaryScreen.Bounds.Size, CopyPixelOperation.SourceCopy);
bmpScreenshot.Save(fileName, ImageFormat.Png);
}
private void OnElapsedTime(object source, ElapsedEventArgs e)
{
TraceService();
}
}
What i have missed in here..
EDIT : when i tick on allow service to interact with desktop
then it shows following error in log.
Service cannot be started. System.Runtime.InteropServices.ExternalException (0x80004005): A generic error occurred in GDI+.
at System.Drawing.Image.Save(String filename, ImageCodecInfo encoder, EncoderParameters encoderParams)
at ScreenCaptureService.ScreenCaptureService.TraceService() in d:\SourceControl\Test\Test\ScreenCapture\ScreenCaptureService\ScreenCaptureService.cs:line 66
at ScreenCaptureService.ScreenCaptureService.OnStart(String[] args) in d:\SourceControl\Test\Test\ScreenCapture\ScreenCaptureService\ScreenCaptureService.cs:line 32
at System.ServiceProcess.ServiceBase.ServiceQueuedMainCallback(Object state)