You should have encountered this problem in your daily work: You need to take screenshots on the application interface and copy the screenshots to other documents for use. We usually use some screenshot software or "Ctrl + PrtSc". This article describes how to copy the UI Unit directly to the clipboard as an image in the WPF program, to create a Snapshot for the application interface.
Take the previous article "WPF employee card" as an example. First, add a custom Command (Command): CopyUI for the program. The shortcut key of this command is "Ctrl + U". Two types of events CanExecute and Executed are defined in the command. For more information about custom commands, see here.
<Window.Resources> <Storyboard x:Key="flashClose"> ... ... </Storyboard> <RoutedUICommand x:Key="CopyUI" Text="Copy WPF UI as Image" /></Window.Resources><Window.InputBindings> <KeyBinding Modifiers="Ctrl" Key="U" Command="{StaticResource CopyUI}"/></Window.InputBindings><Window.CommandBindings> <CommandBinding Command="{StaticResource CopyUI}" CanExecute="CommandBinding_CanExecute" Executed="CommandBinding_Executed"/></Window.CommandBindings>
After the definition of the command is complete, you can fill them up.
private void CommandBinding_CanExecute(object sender, CanExecuteRoutedEventArgs e){ e.CanExecute = true;}private void CommandBinding_Executed(object sender, ExecutedRoutedEventArgs e){ CopyUIElementToClipboard(this.empCard);}
Some friends may have found that the CopyUIElementToClipboard method in the CommandBinding_Executed event is the key part. EmpCard is the overall UI structure of employee cards. Use CopyUIElementToClipboard to draw the wpf ui unit into an image and copy it to the clipboard. The following code:
public static void CopyUIElementToClipboard(FrameworkElement ui){ double width = ui.ActualWidth; double height = ui.ActualHeight; RenderTargetBitmap bmp = new RenderTargetBitmap((int)Math.Round(width), (int)Math.Round(height), 96, 96, PixelFormats.Default); DrawingVisual dv = new DrawingVisual(); using (DrawingContext dc = dv.RenderOpen()) { VisualBrush vb = new VisualBrush(ui); dc.DrawRectangle(vb, null,
new Rect(new Point(), new Size(width, height))); } bmp.Render(dv); Clipboard.SetImage(bmp);}
Next, run the program and press Ctrl + U to copy the UI.
"Ctrl + V" to the Word effect, so that you can easily copy the UI structure, of course, you can also copy the bar chart generated in the program, put it in the PPT for use as a report.