###前提・実現したいこと
C#でWindowsのサービスを作成しているのですが、CopyFromScreenで画面をキャプチャしようとすると例外が出てしまい、できません。
どうやらスクリーンの幅・高さも正しく取得できていないようです。
(System.Windows.Forms.Screen.PrimaryScreen.Bounds)
CopyFromScreenをOnStartメソッドに書いたりMainメソッドにも書いたりしましたが、同じような例外が発生してしまいます。
サービスではなくフォームアプリケーションやコンソールアプリケーションでプロジェクトを作り、CopyFromScreenのコードを同じように書くときちんと動作するのですが・・・
やはりサービスでは画面キャプチャはできないのでしょうか。
解決方法などをご存じの方はご教示ください。
###ソースコード
Program.cs
c#
1using System.ServiceProcess; 2 3namespace RemotePC { 4 class Program { 5 static void Main(string[] args) { 6 ServiceBase[] services = new ServiceBase[] { new RemotePCService() }; 7 ServiceBase.Run(services); 8 } 9 } 10}
RemotePCService.cs (ここで例外が発生します)
c#
1using System; 2using System.Diagnostics; 3using System.Drawing; 4using System.Drawing.Imaging; 5using System.IO; 6using System.Net; 7using System.ServiceProcess; 8using System.Timers; 9 10namespace RemotePC { 11 public partial class RemotePCService : ServiceBase { 12 Timer timer; 13 Rectangle ScreenBounds; 14 15 public RemotePCService() { 16 InitializeComponent(); 17 } 18 19 protected override void OnStart(string[] args) { 20 base.OnStart(args); 21 22 ScreenBounds = System.Windows.Forms.Screen.PrimaryScreen.Bounds; 23 24 timer = new Timer(); 25 timer.Interval = 2000; 26 timer.Elapsed += timer_Elapsed; 27 28 EventLog.WriteEntry("OnStart", EventLogEntryType.Information); 29 } 30 31 protected override void OnStop() { 32 base.OnStop(); 33 EventLog.WriteEntry("OnStop", EventLogEntryType.Information); 34 } 35 36 #endregion 37 38 private void timer_Elapsed(object sender, ElapsedEventArgs e) { 39 timer.Stop(); 40 41 try { 42 using(Bitmap bmp = new Bitmap(ScreenBounds.Width, ScreenBounds.Height, PixelFormat.Format32bppArgb)) { 43 using(Graphics g = Graphics.FromImage(bmp)) { 44 g.CopyFromScreen(new Point(0, 0), new Point(0, 0), bmp.Size); 45 //????ここで例外が発生しているようです。 46 } 47 48 bmp.Save("C:\Users\...\Desktop\Test.bmp"); 49 } 50 } catch(Exception ex) { 51 EventLog.WriteEntry(ex.ToString(), EventLogEntryType.Warning); 52 } 53 54 timer.Start(); 55 } 56 } 57}
発生する例外
System.ComponentModel.Win32Exception (0x80004005): ハンドルが無効です。 場所 System.Drawing.Graphics.CopyFromScreen(Int32 sourceX, Int32 sourceY, Int32 destinationX, Int32 destinationY, Size blockRegionSize, CopyPixelOperation copyPixelOperation) 場所 System.Drawing.Graphics.CopyFromScreen(Point upperLeftSource, Point upperLeftDestination, Size blockRegionSize) 場所 RemotePC.RemotePCService.timer_Elapsed(Object sender, ElapsedEventArgs e)
###補足情報
- Visual Studio 2015
- .NET Framework 4.5
- C# 6.0
回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
退会済みユーザー
2016/02/23 10:14