I'm trying to use use code get a screenshot in Mono C# but I'm getting a System.NotImplementedException when I call CopyFromScreen. My code works with .NET, so is there an alternate way of getting a screenshot using Mono?
Bitmap bitmap = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height);
Graphics graphics = Graphics.FromImage(bitmap as Image);
graphics.CopyFromScreen(0, 0, 0, 0, bitmap.Size);
System.IO.MemoryStream memoryStream = new System.IO.MemoryStream();
bitmap.Save(memoryStream, imageFormat);
bitmap.Save(@"\tmp\screenshot.png", ImageFormat.Png);
I am using Mono JIT compiler version 2.4.2.3 (Debian 2.4.2.3+dfsg-2)
UPDATE: Mono cannot take screenshots. Sad. Lame.
With Mono 2.4.4 you can get the whole screen without GTK#:
public static class MonoScreenShooter { public static void TakeScreenshot(string filePath) { using (Bitmap bmpScreenCapture = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height)) { using (Graphics g = Graphics.FromImage(bmpScreenCapture)) { g.CopyFromScreen(Screen.PrimaryScreen.Bounds.X, Screen.PrimaryScreen.Bounds.Y, 0, 0, bmpScreenCapture.Size, CopyPixelOperation.SourceCopy); } bmpScreenCapture.Save(filePath, System.Drawing.Imaging.ImageFormat.Jpeg); } } } }
I guess an alternative would be using gtk# to get a screenshot. You would need to create a mono project with GTK# support, after that following code should execute:
you could also use P\Invoke and call GTK functions directly.
hope this helps, regards
We had the same problem when we needed to take screenshots with Mono on Linux and OS X in the same software.
Actually, you can use
CopyFromScreen
on Mono on Linux. However you need to install mono-complete package, which includes System.Drawing.For OS X the most reliable way is to Process.Start the
screencapture
command line tool. It is present there by default.For Linux, to make it reliable, one can use either
import
command line from ImageMagic (you'll need to make it a dependency in this case), or force dependency onmono-complete
package which includes System.Drawing. Gtk# approach is unreliable according to our tests and may provide blank screens or fail with exception (and we take thousands of screenshots on various machines every day).Another thing is that when you need to capture multiple displays in one screenshot, you have to properly align separate screenshots after taking those separately via CopyFromScreen.
So we have this solution so far:
Or install it via NuGet (disclaimer: I'm the author):
We use it heavily in our product on many setups, so we periodically improve the code and put notes into blog.