即使有很多关于这个问题的问题,我也找不到合适的解决方案。我正在创建 Windows 服务来捕获屏幕(Windows 7)。(我尝试使用 Windows 应用程序,它工作正常。)
当我要启动服务时,它说我无法启动服务。当我检查 Windows 日志时,它提到了以下错误。
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)
我的代码如下:
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();
}
}
我在这里错过了什么..
编辑:当我打勾时,allow service to interact with desktop
它会在日志中显示以下错误。
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)