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

标签 c# windows winapi unity3d rdp

在使用全屏 3D 应用程序(例如游戏)时是否可以将桌面渲染成屏幕截图?还是在游戏运行时windows会关闭渲染引擎?

我正在寻找在我的游戏中将桌面渲染成纹理的方法。类似 RDP 的协议(protocol)可以成为解决方案吗?

编辑:澄清一下,是否有任何深层次的 api 机制来强制渲染到另一个缓冲区,例如在制作屏幕截图时。不管是 Windows 7 还是 Windows 8/9。

最佳答案

您可以通过在桌面窗口的hWnd 上调用PrintWindow Win32 API 函数来获取屏幕截图。我在 Windows 7 和 Windows 8.1 上试过这个,它甚至在另一个应用程序 (VLC Player) 全屏运行时也能正常工作,所以它有可能也适用于游戏。这只会让您看到没有任务栏的桌面图像,但不会显示任何其他可见的正在运行的应用程序。如果您也需要这些,那么您还需要获取它们的 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); 
  }
}

关于c# - 在全屏 3D 应用程序中获取桌面屏幕截图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25500137/

相关文章:

c# - 生成 .rdlc 报告在本地有效,但在部署到 azure 后无效

c# - Realm Xamarin - GetInstance() 错误

c# - 将值绑定(bind)到复杂类型

c# - NotifyIcon.ShowBalloonTip 不保持超时

windows - 什么是 WINAPI_FAMILY_ONECORE_APP?

c# - 在共享 (.shproj) 项目中添加引用

windows - 在 Windows x64 上构建 OpenJDK8

c - 构建 Win32 GUI 代码

windows - NASM 教程使用 int 80h,但这不适用于 Windows

c# - PssCreateSnapshot - 访问被拒绝的奇怪情况