• 一起谈.NET技术,将WPF UI单元复制到剪贴板 狼人:


      大家在日常工作中应该遇到过这样的问题:需要对应用程序界面进行截屏操作,然后将截屏内容拷贝到其他文档中使用。通常情况下我们会使用一些截屏软件或者“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 进行复制。

    image

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

    image

  • 相关阅读:
    11. Container With Most Water(装最多的水 双指针)
    64. Minimum Path Sum(最小走棋盘 动态规划)
    数组相关
    88. Merge Sorted Array(从后向前复制)
    京东AI平台 春招实习生面试--NLP(offer)
    54. Spiral Matrix(矩阵,旋转打印)
    48. Rotate Image(旋转矩阵)
    春招实习--阿里 蚂蚁金服 支付宝 机器学习面试
    26. Remove Duplicates from Sorted Array(删除排序数组中的重复元素,利用排序的特性,比较大小)
    7. Reverse Integer(翻转整数)
  • 原文地址:https://www.cnblogs.com/waw/p/2163116.html
Copyright © 2020-2023  润新知