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);

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Jakub Jóźwicki
Jakub Jóźwicki

No responses yet

Write a response