在Universal Apps中捕获当前网站的屏幕截图

时间:2015-12-03 17:34:48

标签: c# .net windows windows-10 win-universal-app

以下是我如何捕捉当前网页的屏幕截图,但有时它只捕获webview的可见区域(用户实际看到的内容)。 但我不确定是什么问题。 我认为var heightString = await WebView.InvokeScriptAsync("eval", new[] { "document.body.scrollHeight.toString()" })已经太晚了 - 但程序应该在if (!int.TryParse(heightString, out height))等待完成......我错了吗?

private async Task CaptureWebView()
{
    int width;
    int height;
    var originalWidth = WebView.Width;
    var originalHeight = WebView.Height;
    // ask the content its width
    var widthString = await WebView.InvokeScriptAsync("eval", new[] { "document.body.scrollWidth.toString()" });
    // ask the content its height
    var heightString = await WebView.InvokeScriptAsync("eval", new[] { "document.body.scrollHeight.toString()" });
    if (!int.TryParse(widthString, out width))
    {
        throw new Exception("Unable to get page width");
    }
    if (!int.TryParse(heightString, out height))
    {
        throw new Exception("Unable to get page height");
    }

    // resize the webview to the content
    WebView.Width = width;
    WebView.Height = height;

    await DoCapture("captured.png");

    WebView.Width = originalWidth;
    WebView.Height = originalHeight;

    Painter.Width = width;
    Painter.Height = height;

    var i = await LoadCaptured("captured.png");
    Painter.Fill = i;
}

测试存储库on Github

1 个答案:

答案 0 :(得分:3)

最后问题本身就是WebView.CapturePreviewToStreamAsync()方法。我用它来捕捉完整的网页截图,但它并没有很好地工作。但后来我发现WebViewBrush并意识到这是正确的方法。

所以这里是最终的代码段或GitHub

private async Task CaptureWebView()
{
    int width;
    int height;
    var originalWidth = WebView.ActualWidth;
    var originalHeight = WebView.ActualHeight;

    var widthString = await WebView.InvokeScriptAsync("eval", new[] { "document.body.scrollWidth.toString()" });
    var heightString = await WebView.InvokeScriptAsync("eval", new[] { "document.body.scrollHeight.toString()" });

    if (!int.TryParse(widthString, out width))
    {
        throw new Exception("Unable to get page width");
    }
    if (!int.TryParse(heightString, out height))
    {
        throw new Exception("Unable to get page height");
    }

    // resize the webview to the content
    WebView.Width = width;
    WebView.Height = height;

    var brush = new WebViewBrush();
    brush.SetSource(WebView);

    Painter.Width = width;
    Painter.Height = height;
    Painter.Fill = brush;
}