轉帖|其它|編輯:郝浩|2011-03-16 11:24:04.000|閱讀 914 次
概述:大家在日常工作中應該遇到過這樣的問題:需要對應用程序界面進行截屏操作,然后將截屏內容拷貝到其他文檔中使用。通常情況下我們會使用一些截屏軟件或者“Ctrl+PrtSc ”,本篇將介紹如何在WPF 程序中將UI 單元直接以圖片形式復制到剪貼板,以達到為應用程序界面制作快照(Snapshot)的功能。
# 界面/圖表報表/文檔/IDE等千款熱門軟控件火熱銷售中 >>
大家在日常工作中應該遇到過這樣的問題:需要對應用程序界面進行截屏操作,然后將截屏內容拷貝到其他文檔中使用。通常情況下我們會使用一些截屏軟件或者“Ctrl+PrtSc ”,本篇將介紹如何在WPF 程序中將UI 單元直接以圖片形式復制到剪貼板,以達到為應用程序界面制作快照(Snapshot)的功能。
以我之前做過的一個“WPF 員工卡”的文章為例。首先,要為程序添加一個自定義命令(Command):CopyUI。該命令的快捷鍵方式為“Ctrl+U”,在命令中定義兩種事件CanExecute、Executed。
using System;
using System.Windows;
using System.Windows.Forms.Integration;
using AxShockwaveFlashObjects;
namespace WpfFlash
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void FlashLoaded(object sender, RoutedEventArgs e)
{
WindowsFormsHost formHost = new WindowsFormsHost();
AxShockwaveFlash axShockwaveFlash = new AxShockwaveFlash();
formHost.Child = axShockwaveFlash;
mainGrid.Children.Add(formHost);
string flashPath = Environment.CurrentDirectory;
flashPath += @"\game.swf";
axShockwaveFlash.Movie = flashPath;
}
}
}
<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 進行復制。
“Ctrl+V” 到Word 后的效果,這樣就可以比較方便的復制UI 結構,當然也可以復制程序中生成的柱狀圖,放到PPT中做為報告使用。
本站文章除注明轉載外,均為本站原創或翻譯。歡迎任何形式的轉載,但請務必注明出處、不得修改原文相關鏈接,如果存在內容上的異議請郵件反饋至chenjj@fc6vip.cn
文章轉載自:{GnieTech}