Frage

My application runs fine for about 5 minutes, then it will throw some random System.ArgumentException as seen in the screenshot below: The big problem here is that both arguments actually seem to be correct, and it works perfectly fine for about 5 minutes. My application simply keeps taking snapshots of the screen in a separate Thread.

The following code takes the snapshot of the screen, and a System.ArgumentException is caused in this snippet (same as in the screenshot).

Bitmap SNew = new Bitmap(NewRes.Width, NewRes.Height);
using (Graphics g = Graphics.FromImage(SNew))
    g.CopyFromScreen(0, 0, 0, 0, new Size(NewRes.Width, NewRes.Height));

The same exception may also occur at the CopyFromScreen method, with the same seemingly correct NewRes values (while not occuring at the first line in my snippet):

An unhandled exception of type 'System.ArgumentException' occurred in System.Drawing.dll


If I put this code in a try { } catch { } clause, it works fine as well (the exception does not occur anymore after the exception pops up in the log for about 10 times). This is of course not a great solution, and sometimes it just keeps hanging within that exception forever, not taking screenshots at all until I restart the application.

I have no idea why the arguments are invalid and what may cause this. Any ideas?

War es hilfreich?

Lösung

What I can provide to you with certainty is a concrete alternative that will produce the same output but instead of using CopyFromScreen using platform invoke to interop with the Windows API directly. You can find a full example here, curtosy of Hans Passant as a response to a question here.

I can't however, tell you with certainty why you're experiencing the exception but I can deduce from other sources such as this thread (incidentally featuring Hans again as nobugz) and from my own experiences that CopyFromScreen is buggy and in this case, could be suffering from a memory leak. Considering the thread I linked, what version of the .NET Framework is your target framework?

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top