C# code snippet to get a screenshot of a process
A small code snippet to get a screenshot of a process
Screenshot of this application.
Code behinds
using System; using System.Diagnostics; using System.Drawing; using System.Drawing.Imaging; using System.IO; using System.Runtime.InteropServices; using System.Windows.Forms; namespace ProcessScreenshot { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void btnTake_Click(object sender, EventArgs e) { Process[] ps = Process.GetProcessesByName(txtProcess.Text.Trim()); if (ps.Length == 0) { MessageBox.Show(string.Format("There is no process named {0}", txtProcess.Text)); return; } Process proc = Process.GetProcessesByName("notepad")[0]; if (SetForegroundWindow(proc.MainWindowHandle)) { RECT srcRect; if (!proc.MainWindowHandle.Equals(IntPtr.Zero)) { if (GetWindowRect(proc.MainWindowHandle, out srcRect)) { int width = srcRect.Right - srcRect.Left; int height = srcRect.Bottom - srcRect.Top; var bmp = new Bitmap(width, height); Graphics screenG = Graphics.FromImage(bmp); try { screenG.CopyFromScreen(srcRect.Left, srcRect.Top, 0, 0, new Size(width, height), CopyPixelOperation.SourceCopy); if (!Directory.Exists(txtPath.Text)) Directory.CreateDirectory(txtPath.Text); string fileName = DateTime.Now.ToString("HHmmss-") + Guid.NewGuid().ToString().Substring(0, 6) + ".png"; bmp.Save(Path.Combine(txtPath.Text.Trim(), fileName), ImageFormat.Png); } catch (Exception ex) { MessageBox.Show(ex.Message); } finally { screenG.Dispose(); bmp.Dispose(); } } } } } [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] private static extern bool GetWindowRect(IntPtr hWnd, out RECT lpRect); [DllImport("user32.dll", ExactSpelling = true, CharSet = CharSet.Auto)] [return: MarshalAs(UnmanagedType.Bool)] private static extern bool SetForegroundWindow(IntPtr hWnd); #region Nested type: RECT [StructLayout(LayoutKind.Sequential)] public struct RECT { public int Left; public int Top; public int Right; public int Bottom; } #endregion } }
