C#/WPF 自制截图工具

时间:2024-07-06 07:05:44

        在日常使用电脑办公时,我们经常遇到需要截图然后保存图片,我们往往需要借助安装截图工具才能实现,现在我们通过C#自制截图工具,也能够轻松进行截图。

我们可以通过C#调用WindousAPI来实现截图,实例代码如下:


        /// <summary>
        /// 调用API函数获取整个屏幕的图像
        /// </summary>
        /// <returns></returns>
        [DllImport("user32.dll", EntryPoint = "GetDesktopWindow")]
        private static extern IntPtr GetDesktopWindow();

        [DllImport("user32.dll", EntryPoint = "GetWindowDC")]
        private static extern IntPtr GetWindowDC(IntPtr hwnd);

        [DllImport("gdi32.dll", EntryPoint = "BitBlt")]
        private static extern int BitBlt(
            IntPtr hDestDC,
            int x,
            int y,
            int nWidth,
            int nHeight,
            IntPtr hSrcDC,
            int xSrc,
            int ySrc,
            int dwRop
        );

        /// <summary>
        /// 截取整个屏幕的图像
        /// </summary>
        /// <returns></returns>
        public static Bitmap CopyFromScreen()
        {
            int width = (int)SystemParameters.PrimaryScreenWidth;
            int height = (int)SystemParameters.PrimaryScreenHeight;
            Bitmap newBitmap = new Bitmap(width, height);
            Graphics g = Graphics.FromImage(newBitmap);

            IntPtr DeskHwnd = GetWindowDC(GetDesktopWindow());
            IntPtr Ghwnd = g.GetHdc();

            BitBlt(Ghwnd, 0, 0, width, height, DeskHwnd, 0, 0, 13369376);
            g.ReleaseHdc(Ghwnd);

            CopyHelper.newBitmap = newBitmap;
            return newBitmap;
        }

实例链接:https://download.****.net/download/lvxingzhe3/89505005