C# PrintScreen源代码/模拟

C# PrintScreen源代码/模拟,c#,bitmap,sendkeys,screen-capture,printscreen,C#,Bitmap,Sendkeys,Screen Capture,Printscreen,我想拍一张全屏direct3D游戏的照片。我知道我需要创建一个在c语言中更难的覆盖,我发现使用printscreen并将其粘贴到mspaint中确实可以捕获游戏窗口 我最终得到了一个不稳定的代码: try { SendKeys.SendWait("{PRTSC}"); Thread.Sleep(100); if (Clipboard.ContainsIm

我想拍一张全屏direct3D游戏的照片。我知道我需要创建一个在c语言中更难的覆盖,我发现使用printscreen并将其粘贴到mspaint中确实可以捕获游戏窗口

我最终得到了一个不稳定的代码:

            try
            {
                SendKeys.SendWait("{PRTSC}");
                Thread.Sleep(100);
                if (Clipboard.ContainsImage())
                    return Clipboard.GetImage();
            }
            catch (Exception)
            {
                throw;
            }
            Bitmap bitmap = new Bitmap(1, 1);
            return bitmap;
这段代码有时有效,有时抛出ExternalException,有时和Clipboard.ContainsImage返回false,只返回1,1大小的图像

我想尝试改进这段代码,这样我就不必依赖于用thread.sleep20000将某些内容复制到剪贴板所需的时间。虽然可以,但这段代码只是更大代码的一部分,每800毫秒执行一次


因此,我需要了解如何更可靠地发送密钥或获取printscreen使用的方法。

可能的副本看起来很有趣,但为什么我不能创建一个新设备?Device Device=new Device0,DeviceType.Default,GetForeGroundIndow,CreateFlags.None,new PresentParameters;上面说把手可能有问题?在direct3d游戏中,图片是黑色的
public static class Win32
{
    [DllImport("User32.dll", SetLastError = true)]
    [return: MarshalAs(UnmanagedType.Bool)]
    public static extern bool PrintWindow(IntPtr hwnd, IntPtr hDC, uint nFlags);
}

public Bitmap CaptureWindow()
{
    Bitmap bmp = new Bitmap(this.Width,this.Height);
    using (Graphics g = Graphics.FromImage(bmp))
    {
        Win32.PrintWindow(this.Handle, g.GetHdc(), 0);
        g.ReleaseHdc();
    }
    return bmp;
}