屏幕截图非活动外部应用程序

Screenshot non-active external application

我需要截取非活动外部应用程序的屏幕截图,例如 TeamSpeak 或 Skype。

我已经搜索过但没有找到太多,我知道无法对最小化的应用程序进行截图,但我认为应该可以对非活动应用程序进行截图。

PS : 我只想截图应用程序,所以如果另一个应用程序在我想要的应用程序之上,会不会有问题?

我现在没有代码,我找到了一个 user32 API 可以做我想做的,但我忘记了名字..

感谢您的帮助。

使用来自 user32 API 的 GetWindowRect coupled with PrintWindow 应该是实现该功能所需的全部。 PrintWindow 将正确捕获特定应用程序的内容,即使它被上面的另一个 window 遮挡了。

值得注意的是,这可能不适用于捕获 DirectX 的内容 windows。

您要找的 API 是 PrintWindow:

void Example()
{
    IntPtr hwnd = FindWindow(null, "Example.txt - Notepad2");
    CaptureWindow(hwnd);
}

[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", SetLastError = true)]
static extern IntPtr FindWindow(string lpClassName, string lpWindowName);

public void CaptureWindow(IntPtr handle)
{
    // Get the size of the window to capture
    Rectangle rect = new Rectangle();
    GetWindowRect(handle, ref rect);

    // GetWindowRect returns Top/Left and Bottom/Right, so fix it
    rect.Width = rect.Width - rect.X;
    rect.Height = rect.Height - rect.Y;

    // Create a bitmap to draw the capture into
    using (Bitmap bitmap = new Bitmap(rect.Width, rect.Height))
    {
        // Use PrintWindow to draw the window into our bitmap
        using (Graphics g = Graphics.FromImage(bitmap))
        {
            IntPtr hdc = g.GetHdc();
            if (!PrintWindow(handle, hdc, 0))
            {
                int error = Marshal.GetLastWin32Error();
                var exception = new System.ComponentModel.Win32Exception(error);
                Debug.WriteLine("ERROR: " + error + ": " + exception.Message);
                // TODO: Throw the exception?
            }
            g.ReleaseHdc(hdc);
        }

        // Save it as a .png just to demo this
        bitmap.Save("Example.png");
    }
}