NoWar
NoWar

Reputation: 37632

Screenshot of the main WPF window under second monitor/TV

I use my application on the second monitor and sometimes at the primary monitor of the computer.

How I can get screenshot of the second monitor?

The following code doesn't work for the second monitor...

Graphics gfx;
Bitmap bmp = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height);
gfx = Graphics.FromImage(bmp);
gfx.CopyFromScreen(Screen.PrimaryScreen.Bounds.X, Screen.PrimaryScreen.Bounds.Y, 0, 0, Screen.PrimaryScreen.Bounds.Size, CopyPixelOperation.SourceCopy);

MemoryStream ms = new MemoryStream();
bmp.Save(ms, ImageFormat.Jpeg);
byte[] bitmapData = ms.ToArray();

Upvotes: 2

Views: 969

Answers (2)

Albin Sunnanbo
Albin Sunnanbo

Reputation: 47058

Use Screen.AllScreens[1].Bounds isntead of Screen.PrimaryScreen.Bounds.

Or more reliable to get the first non Primary Screen.

var secondScreen = Screen.AllScreens.Where(screen => !screen.Primary).FirstOrDefault();

check for secondScreen == null to know if you have a secondScreen.

Edit:
You might also be interested in Screen.FromControl that gives the screen that the application is currently running on.

Upvotes: 3

Jay
Jay

Reputation: 57959

That code does not work for your second screen because it is explicitly using Screen.PrimaryScreen.

If you want to pull from the second display explicitly (ignoring the case where you have 3…n displays), you can replace PrimaryScreen with AllScreens[1].

Keep in mind that this will break if you ever disconnect that second display.

It sounds like maybe you want to be capturing your application window instead of the screen, in case the application isn't taking up the whole screen or straddles two screens. WPF has this capability natively: Get System.Drawing.Bitmap of a WPF Area using VisualBrush

Upvotes: 1

Related Questions