大家在日常工作中应该遇到过这样的问题:需要对应用程序界面进行截屏操作,然后将截屏内容拷贝到其他文档中使用。通常情况下我们会使用一些截屏软件或者“Ctrl+PrtSc ”,本篇将介绍如何在WPF 程序中将UI 单元直接以图片形式复制到剪贴板,以达到为应用程序界面制作快照(Snapshot)的功能。

     以我之前做过的一个“WPF 员工卡”的文章为例。首先,要为程序添加一个自定义命令(Command):CopyUI。该命令的快捷键方式为“Ctrl+U”,在命令中定义两种事件CanExecute、Executed。关于自定义命令可以参考这里。

<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>  

完成命令的定义后,就可以为它们添油加醋了。

private void CommandBinding_CanExecute(object sender, CanExecuteRoutedEventArgs e)  {      e.CanExecute = true;  }    private void CommandBinding_Executed(object sender, ExecutedRoutedEventArgs e)  {      CopyUIElementToClipboard(this.empCard);  }

     到这里有些朋友可能已经发现CommandBinding_Executed 事件里CopyUIElementToClipboard 方法才是关键部分。empCard 是员工卡整体UI 结构。通过CopyUIElementToClipboard 将WPF UI 单元绘制成图片并复制到剪贴板中,如下代码:

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); }

接下来运行程序,按“Ctrl+U” 对UI 进行复制。

将WPF UI单元复制到剪贴板_第1张图片

“Ctrl+V” 到Word 后的效果,这样就可以比较方便的复制UI 结构,当然也可以复制程序中生成的柱状图,放到PPT中做为报告使用。

将WPF UI单元复制到剪贴板_第2张图片