將WPF UI單元復制到剪貼板

作者: Gnie  來源: 博客園  發布時間: 2010-12-20 22:48  閱讀: 1324 次  推薦: 0   原文鏈接   [收藏]  

  大家在日常工作中應該遇到過這樣的問題:需要對應用程序界面進行截屏操作,然后將截屏內容拷貝到其他文檔中使用。通常情況下我們會使用一些截屏軟件或者“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

0
0
 
標簽:WPF
 
 

文章列表

arrow
arrow
    全站熱搜
    創作者介紹
    創作者 大師兄 的頭像
    大師兄

    IT工程師數位筆記本

    大師兄 發表在 痞客邦 留言(0) 人氣()