轉(zhuǎn)帖|其它|編輯:郝浩|2011-03-16 11:24:04.000|閱讀 914 次
概述:大家在日常工作中應(yīng)該遇到過這樣的問題:需要對應(yīng)用程序界面進(jìn)行截屏操作,然后將截屏內(nèi)容拷貝到其他文檔中使用。通常情況下我們會(huì)使用一些截屏軟件或者“Ctrl+PrtSc ”,本篇將介紹如何在WPF 程序中將UI 單元直接以圖片形式復(fù)制到剪貼板,以達(dá)到為應(yīng)用程序界面制作快照(Snapshot)的功能。
# 界面/圖表報(bào)表/文檔/IDE等千款熱門軟控件火熱銷售中 >>
大家在日常工作中應(yīng)該遇到過這樣的問題:需要對應(yīng)用程序界面進(jìn)行截屏操作,然后將截屏內(nèi)容拷貝到其他文檔中使用。通常情況下我們會(huì)使用一些截屏軟件或者“Ctrl+PrtSc ”,本篇將介紹如何在WPF 程序中將UI 單元直接以圖片形式復(fù)制到剪貼板,以達(dá)到為應(yīng)用程序界面制作快照(Snapshot)的功能。
以我之前做過的一個(gè)“WPF 員工卡”的文章為例。首先,要為程序添加一個(gè)自定義命令(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);
}
到這里有些朋友可能已經(jīng)發(fā)現(xiàn)CommandBinding_Executed 事件里CopyUIElementToClipboard 方法才是關(guān)鍵部分。empCard 是員工卡整體UI 結(jié)構(gòu)。通過CopyUIElementToClipboard 將WPF UI 單元繪制成圖片并復(fù)制到剪貼板中,如下代碼:
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);
}
接下來運(yùn)行程序,按“Ctrl+U” 對UI 進(jìn)行復(fù)制。
“Ctrl+V” 到Word 后的效果,這樣就可以比較方便的復(fù)制UI 結(jié)構(gòu),當(dāng)然也可以復(fù)制程序中生成的柱狀圖,放到PPT中做為報(bào)告使用。
本站文章除注明轉(zhuǎn)載外,均為本站原創(chuàng)或翻譯。歡迎任何形式的轉(zhuǎn)載,但請務(wù)必注明出處、不得修改原文相關(guān)鏈接,如果存在內(nèi)容上的異議請郵件反饋至chenjj@fc6vip.cn
文章轉(zhuǎn)載自:{GnieTech}