Sep 28, 2023
How to make screenshot in C#
[DllImport("user32.dll", SetLastError = true)]
static extern IntPtr GetDC(IntPtr hWnd);
[DllImport("user32.dll", SetLastError = true)]
static extern IntPtr WindowFromDC(IntPtr hdc);
[DllImport("user32.dll")]
static extern bool GetWindowRect(IntPtr hWnd, ref RECT rect);
[DllImport("gdi32.dll", EntryPoint = "BitBlt", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool BitBlt([In] IntPtr hdc, int nXDest, int nYDest, int nWidth, int nHeight, [In] IntPtr hdcSrc, int nXSrc, int nYSrc, uint dwRop);
var src = GetDC(IntPtr.Zero);
RECT r = new RECT();
GetWindowRect(WindowFromDC(src), ref r);
int rW = 2*(r.Right — r.Left); // because we don’t want to get exact DPI scaling
int rH = 2*(r.Bottom — r.Top);
var bmp = new Bitmap(rW, rH);
var g = System.Drawing.Graphics.FromImage(bmp);
var dst = g.GetHdc();
BitBlt(dst, 0, 0, rW, rH, src, 0, 0, 0x00CC0020);
g.ReleaseHdc();
bmp.Save(“screengrab.png”, System.Drawing.Imaging.ImageFormat.Png);