zoukankan      html  css  js  c++  java
  • 一起谈.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

  • 相关阅读:
    CSS Hack大全-教你如何区分出IE6-IE10、FireFox、Chrome、Opera
    详解HTML5中的<aside>元素与<article>元素
    jQuery基于ajax实现星星评论代码
    JS打字效果的动态菜单代码分享
    javascript中alert()与console.log()的区别
    jquery ajax对特殊字符进行转义防止js注入使用示例
    JQuery中each()的使用方法说明
    前端图片延迟加载详细讲解
    表数据查询例题
    shell-4.bash的变量:用户自定义变量
  • 原文地址:https://www.cnblogs.com/waw/p/2163116.html
Copyright © 2011-2022 走看看