C#

C#でscreenをcaptureしてsaveする。

More than 1 year has passed since last update.
using System;
using System.IO;
using System.Windows;

namespace CaptureScreen
{
    class Capture
    {
        /// <summary>
        /// screenをcaptureしてsaveする。
        /// </summary>
        /// <param name="startpoint">開始点</param>
        /// <param name="size">サイズ</param>
        /// <param name="savefolder">保存フォルダorFullpath</param>
        /// <param name="savename">ファイル名(Fullpathを指定するときは空)</param>
        /// <returns></returns>
        public static string CaptureScreen(Point startpoint, Size size, string savefolder, string savename = "")
        {
            //保存パス生成
            string executeTime = (DateTime.Now.ToString("yyyy_MMdd_HHmmss_ffff"));
            string file = savefolder.TrimEnd('\\') + @"\" + executeTime + savename;
            try
            {
                // 保存するBitmap(handWrite)
                var bitmap = new System.Drawing.Bitmap(
                                                                        (int)size.Width,
                                                                        (int)size.Height,
                                                                        System.Drawing.Imaging.PixelFormat.Format32bppArgb);

                try
                {
                    using (var g = System.Drawing.Graphics.FromImage(bitmap))
                    {
                        g.CopyFromScreen(
                            (int)startpoint.X,
                            (int)startpoint.Y,
                            0,
                            0,
                            bitmap.Size,
                            System.Drawing.CopyPixelOperation.SourceCopy);
                    }
                }
                catch (Exception exception) {
                    string error = savefolder + file + exception.Message;
                }

                //fullpathを指定した場合。
                if (savename == "")
                {
                    file = savefolder;
                    savefolder = Path.GetDirectoryName(savefolder);
                }

                if (!Directory.Exists(savefolder))
                    Directory.CreateDirectory(savefolder);

                try
                {
                    bitmap.Save(file, System.Drawing.Imaging.ImageFormat.Jpeg);
                }
                catch (Exception exception)
                {
                    string error = savefolder + file + exception.Message;
                }
                bitmap.Dispose();
            }
            catch (Exception exception) {
                string error = savefolder + file + exception.Message;
            }
            return file;
        }
    }
}