截图WPF应用程序

本文关键字:应用程序 WPF 截图 | 更新日期: 2023-09-27 17:53:57

我有一个WPF应用程序,我们想在其中使用后面的代码实现截图的功能。

当我们想要的时候,我们应该能够在用户的机器上截取我们的应用程序的屏幕截图(而不是整个打印屏幕)

为此,我做了一些谷歌,发现DllImport("user32.dll")将帮助我在这方面。然而,我不知道如何使用这个?这里我应该参考哪一种方法?

我试过下面的代码,但没有运气-

[DllImport("User32.dll")]
public static extern int SetForegroundWindow(IntPtr point);
Process p = Process.GetCurrentProcess();
p.WaitForInputIdle();
IntPtr h = p.MainWindowHandle;
SetForegroundWindow(h);
SendKeys.SendWait("k");
IntPtr processFoundWindow = p.MainWindowHandle;

请建议。

截图WPF应用程序

这是我在前面的应用程序中使用的方法。

我创建了一个类来处理截图功能。

public sealed class snapshotHandler
{
    [StructLayout(LayoutKind.Sequential)]
    private struct RECT
    {
        public int m_left;
        public int m_top;
        public int m_right;
        public int m_bottom;
    }
    [DllImport("user32.dll")]
    private static extern IntPtr GetWindowRect(IntPtr hWnd, ref RECT rect);
    public static void Savesnapshot(IntPtr handle_)
    {
        RECT windowRect = new RECT();
        GetWindowRect(handle_, ref windowRect);
        Int32 width = windowRect.m_right - windowRect.m_left;
        Int32 height = windowRect.m_bottom - windowRect.m_top;
        Point topLeft = new Point(windowRect.m_left, windowRect.m_top);
        Bitmap b = new Bitmap(width, height);
        Graphics g = Graphics.FromImage(b);
        g.CopyFromScreen(topLeft, new Point(0, 0), new Size(width, height));
        b.Save(SNAPSHOT_FILENAME, ImageFormat.Jpeg);
    }
}

要使用上述功能,我调用SaveSnapshot方法。

SnapshotHandler.SaveSnapshot(System.Diagnostics.Process.GetCurrentProcess().MainWindowHandle);