在全屏3D应用程序中获取桌面的屏幕截图

时间:2014-08-26 07:18:44

标签: c# windows winapi unity3d rdp

使用全屏3D应用程序(如游戏)时,是否可以将桌面渲染为屏幕截图?或者Windows在游戏运行时关闭渲染引擎?

我正在寻找将桌面渲染成游戏纹理的方法。可以像协议一样使用RDP吗?

编辑:为了澄清,是否有任何深层次的api机制强制渲染到另一个缓冲区,例如屏幕截图。如果它只是Windows 7或Windows 8/9并不重要。

1 个答案:

答案 0 :(得分:5)

您可以通过在桌面窗口的hWnd上调用PrintWindow Win32 API函数来获取屏幕截图。我在Windows 7和Windows 8.1上试过这个,即使在全屏运行另一个应用程序(VLC播放器)时也能正常运行,因此它也有可能与游戏一起使用。这样只会在没有任务栏的情况下为您提供桌面图像,但不会显示其他任何可见的正在运行的应用程序。如果你也需要那些,那么你也需要得到他们的HWND(例如通过枚举所有正在运行的进程并获得它们的窗口句柄),然后使用相同的方法。

using System;
using System.Drawing; // add reference to the System.Drawing.dll
using System.Drawing.Imaging;
using System.IO;
using System.Runtime.InteropServices;

namespace DesktopScreenshot
{
  class Program
  {
    static void Main(string[] args)
    {
        // get the desktop window handle without the task bar
        // if you only use GetDesktopWindow() as the handle then you get and empty image
        IntPtr desktopHwnd = FindWindowEx(GetDesktopWindow(), IntPtr.Zero, "Progman", "Program Manager");

        // get the desktop dimensions
        // if you don't get the correct values then set it manually
        var rect = new Rectangle();
        GetWindowRect(desktopHwnd, ref rect);

        // saving the screenshot to a bitmap
        var bmp = new Bitmap(rect.Width, rect.Height);
        Graphics memoryGraphics = Graphics.FromImage(bmp);
        IntPtr dc = memoryGraphics.GetHdc();
        PrintWindow(desktopHwnd, dc, 0);
        memoryGraphics.ReleaseHdc(dc);

        // and now you can use it as you like
        // let's just save it to the desktop folder as a png file
        string desktopDir = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
        string screenshotPath = Path.Combine(desktopDir, "desktop.png");
        bmp.Save(screenshotPath, ImageFormat.Png);
    }

    [DllImport("User32.dll", SetLastError = true)]
    [return: MarshalAs(UnmanagedType.Bool)]
    static extern bool PrintWindow(IntPtr hwnd, IntPtr hdc, uint nFlags);

    [DllImport("user32.dll")]
    static extern bool GetWindowRect(IntPtr handle, ref Rectangle rect);

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

    [DllImport("user32.dll", CharSet = CharSet.Unicode)]
    static extern IntPtr FindWindowEx(IntPtr parentHandle, IntPtr childAfter, string lclassName, string windowTitle); 
  }
}