WPF take screenshot of application including hidde

2019-08-30 06:34发布

问题:

Under the category "limitations of the technology":

I have received the requirement to have a screenshot button in my application that will take a screenshot and launch a printer dialog. Fair enough. My code achieves that. I simply take my window, and use a RenderTargetBitmap to render the window.

However, the requirement now states that it should include all content that is hidden behind scrollbars. Meaning, that in the screenshot the application should look "stretched" in order to eliminate scrollbars, and show all data. For instance in case there is a large list or datagrid, all the data should be visible.

Keeping in mind that WPF might be virtualizing and not rendering things that are not in view, is there any way I can achieve this requirement? Is there a possibility of rendering the visual tree to a seperate infinite space and taking a screenshot there? Something else?

In response to comments:

The screenshot button is on an outer shell that only holds the menu. Inside this shell any of 800+ views can be hosted. These views could contain datagrids, lists, large forms consisting of textboxes... anything. There is no way to tell what is 'inside' without walking the visual tree.

The functionality requested is similar to printing a webpage in your browser to PDF. It will also give you the entire DOM instead of just what you see in the limited view of the browser.

回答1:

XAML:

<Grid>
    <Button
        x:Name="btnPrint"
        Width="50"
        HorizontalAlignment="Left"
        VerticalAlignment="Top"
        Click="BtnPrint_Click"
        Content="Print" />
    <ScrollViewer Height="500" HorizontalAlignment="Center">
        <Grid x:Name="toPrint">
           <!--your code goes here-->
        </Grid>
    </ScrollViewer>
</Grid>

C#:

private void BtnPrint_Click(object sender, RoutedEventArgs e)
    {
        var pdialog = new PrintDialog();
        if (pdialog.ShowDialog() == true)
        {

            System.Windows.Size pageSize = new System.Windows.Size { Height = pdialog.PrintableAreaHeight, Width = pdialog.PrintableAreaWidth };
            toPrint.Measure(pageSize);
            toPrint.UpdateLayout();
            pdialog.PrintVisual(toPrint, "Print");

        }
    }