Tips&Tricks I trucchi del mestiere

 

Un cattura schermo facile facileà


Il tip in allegato illustra come effettuare la cattura dello schermo in C# (utilizzando l'api di Windows BitBlt) e salvare l'immagine catturata in un file bitmap.
Tip fornito dal sig. A.Pelleriti

using System;
using System.Drawing;
using System.Runtime.InteropServices;

class CatturaSchermo
{

	 [DllImport("gdi32.dll")]
	 public static extern bool BitBlt(IntPtr hdcDst, int xDst, int yDst, int cx, int cy,
									  IntPtr hdcSrc, int xSrc, int ySrc, 
uint ulRop);

	 public static void Main(string[] args)
	 {
		 string filename=@"C:\cattura.bmp";
		 if(args.Length>0)
			filename=args[0];

		 Graphics gfxScreen = Graphics.FromHwnd(IntPtr.Zero);

		 Bitmap bmp = new Bitmap((int) gfxScreen.VisibleClipBounds.Width,
						  (int) gfxScreen.VisibleClipBounds.Height, 
gfxScreen);

		 Graphics gfxBitmap = Graphics.FromImage(bmp);

		 IntPtr hdcScreen = gfxScreen.GetHdc();
		 IntPtr hdcBitmap = gfxBitmap.GetHdc();

		 BitBlt(hdcBitmap,
				0, 0,
				bmp.Width, bmp.Height,
				hdcScreen,
				0, 0,
				0x00CC0020);//costante SRCCOPY

		 gfxBitmap.ReleaseHdc(hdcBitmap);
		 gfxScreen.ReleaseHdc(hdcScreen);

		 gfxBitmap.Dispose();
		 gfxScreen.Dispose();

		 bmp.Save(filename);
	 }
}

Per provare il tip basta salvare il codice in un file (ad es. cattura.cs) e compilare con il comando

csc cattura.cs

Quindi, eseguire il comando:

cattura.exe [percorsofile.bmp]

Nel caso in cui non si fornisca il nome del file verrα creato un file c:\cattura.bmp.