C# 获取非前端窗口的截图

版权声明:本文为博主原创文章,转载请注明源地址 https://blog.csdn.net/qq_15505341/article/details/79185346

截取截图

参数为被截图窗口的窗口句柄

        #region GetWindowCapture的dll引用
        [DllImport("user32.dll")]
        private static extern IntPtr GetWindowRect(IntPtr hWnd, ref Rectangle rect);

        [DllImport("gdi32.dll")]
        private static extern IntPtr CreateCompatibleDC(
         IntPtr hdc // handle to DC
         );
        [DllImport("gdi32.dll")]
        private static extern IntPtr CreateCompatibleBitmap(
         IntPtr hdc,         // handle to DC
         int nWidth,      // width of bitmap, in pixels
         int nHeight      // height of bitmap, in pixels
         );
        [DllImport("gdi32.dll")]
        private static extern IntPtr SelectObject(
         IntPtr hdc,           // handle to DC
         IntPtr hgdiobj    // handle to object
         );
        [DllImport("gdi32.dll")]
        private static extern int DeleteDC(
         IntPtr hdc           // handle to DC
         );
        [DllImport("user32.dll")]
        private static extern bool PrintWindow(
         IntPtr hwnd,                // Window to copy,Handle to the window that will be copied.
         IntPtr hdcBlt,              // HDC to print into,Handle to the device context.
         UInt32 nFlags               // Optional flags,Specifies the drawing options. It can be one of the following values.
         );
        [DllImport("user32.dll")]
        private static extern IntPtr GetWindowDC(
         IntPtr hwnd
         );
        #endregion

        public static Bitmap GetWindowCapture(IntPtr hWnd)
        {
            IntPtr hscrdc = GetWindowDC(hWnd);
            Rectangle windowRect = new Rectangle();
            GetWindowRect(hWnd, ref windowRect);
            int width = Math.Abs(windowRect.X - windowRect.Width);
            int height = Math.Abs(windowRect.Y - windowRect.Height);
            IntPtr hbitmap = CreateCompatibleBitmap(hscrdc, width, height);
            IntPtr hmemdc = CreateCompatibleDC(hscrdc);
            SelectObject(hmemdc, hbitmap);
            PrintWindow(hWnd, hmemdc, 0);
            Bitmap bmp = Image.FromHbitmap(hbitmap);
            DeleteDC(hscrdc);//删除用过的对象
            DeleteDC(hmemdc);//删除用过的对象
            return bmp;
        }

原帖-CSDN-thomas_02-C# 非顶端窗口截图 - 用于查找指定窗口并截图


获得任意窗口的句柄

需要调用到FindWindow函数,参数一是欲获取窗口的类名,参数二是欲获取窗口的窗口名,可以只提供一个,另一个给null,成功返回窗口句柄,失败返回0

        [DllImport("user32.dll", EntryPoint = "FindWindow")]
        private extern static IntPtr FindWindow(string lpClassName, string lpWindowName);

利用SPY++获得窗口的类名和窗口名

在vs顶部的菜单栏中,选择 工具-SPY++
这里写图片描述

CTRL+F 打开查找窗口,把中间的东东拉出去拉到你要查的窗口上
这里写图片描述

由此可知图中的类名是“VirtuaNESwndclass”,编写代码得到句柄

            IntPtr intPtr = FindWindow("VirtuaNESwndclass", null);

参考资料
博客园-beautifulzzzz-[WinAPI] 获取窗口句柄的几种方法
博客园-Net-Spider-C# FindWindow用法

猜你喜欢

转载自blog.csdn.net/qq_15505341/article/details/79185346