1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
|
public static BitmapSource CaptureRegion4(
int x, int y, int width, int height, bool addToClipboard)
{
sd.Bitmap bitmap = null;
BitmapSource bitmapsource = null;
//Variable to keep the handle of the btimap.
IntPtr m_HBitmap = IntPtr.Zero;
//Variable to keep the refrence to the desktop bitmap.
System.Drawing.Bitmap bmp = null;
//Here we get the handle to the desktop device context.
IntPtr hDC = User32.GetDC(IntPtr.Zero); //User32.GetDesktopWindow());
LogFile.Add("Get dc = " + hDC);
//Here we make a compatible device context in memory for screen device context.
IntPtr hMemDC = Gdi32.CreateCompatibleDC(hDC);
LogFile.Add("compatible dc = " + hMemDC);
//We create a compatible bitmap of screen size and using screen device context.
m_HBitmap = Gdi32.CreateCompatibleBitmap(hDC, width, height);
LogFile.Add("CreateCompatibleBitmap = " + m_HBitmap);
//As m_HBitmap is IntPtr we can not check it against null. For this purspose IntPtr.Zero is used.
if (m_HBitmap != IntPtr.Zero)
{
//Here we select the compatible bitmap in memeory device context and keeps the refrence to Old bitmap.
IntPtr hOld = (IntPtr)Gdi32.SelectObject(hMemDC, m_HBitmap);
LogFile.Add("before bitblt width = " + width + " height = " + height);
//We copy the Bitmap to the memory device context.
Gdi32.BitBlt(hMemDC, 0, 0, width, height, hDC, 0, 0, Gdi32.SRCCOPY | Gdi32.CAPTUREBLT);
LogFile.Add("after bitblt ");
//We select the old bitmap back to the memory device context.
LogFile.Add("select object hmemdc = " + hMemDC + " hold " + hOld);
Gdi32.SelectObject(hMemDC, hOld);
//Image is created by Image bitmap handle and assigned to Bitmap variable.
LogFile.Add("Bitmap from hbitmap = " + m_HBitmap);
//bitmap = System.Drawing.Image.FromHbitmap(m_HBitmap);
LogFile.Add("new hbitmep " + bitmap);
bitmap = null;
bitmapsource = Imaging.CreateBitmapSourceFromHBitmap(m_HBitmap,
IntPtr.Zero,
Int32Rect.Empty,
System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions());
LogFile.Add("end bitmap source " + bitmap);
//Delete the compatible bitmap object.
Gdi32.DeleteObject(m_HBitmap);
}
//We delete the memory device context.
Gdi32.DeleteDC(hMemDC);
//We release the screen device context.
User32.ReleaseDC(User32.GetDesktopWindow(), hDC);
LogFile.Add("transforme to bitmap source");
if (bitmap != null)
{
bitmapsource = new BitmapToBitmapSource(bitmap).BitmapSource;
LogFile.Add("after transforme to bitmap source");
User32.DeleteObject(bitmap.GetHbitmap());
}
return bitmapsource;
} |
Partager