色尼玛亚洲综合影院,亚洲3atv精品一区二区三区,麻豆freexxxx性91精品,欧美在线91

將WPF UI單元復(fù)制到剪貼板

  大家在日常工作中應(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。關(guān)于自定義命令可以參考這里

<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ù)制。

image

  “Ctrl+V” 到Word 后的效果,這樣就可以比較方便的復(fù)制UI 結(jié)構(gòu),當(dāng)然也可以復(fù)制程序中生成的柱狀圖,放到PPT中做為報(bào)告使用。

image

NET技術(shù)將WPF UI單元復(fù)制到剪貼板,轉(zhuǎn)載需保留來源!

鄭重聲明:本文版權(quán)歸原作者所有,轉(zhuǎn)載文章僅為傳播更多信息之目的,如作者信息標(biāo)記有誤,請第一時(shí)間聯(lián)系我們修改或刪除,多謝。

主站蜘蛛池模板: 汪清县| 齐河县| 依安县| 重庆市| 东丰县| 肇东市| 德江县| 九龙坡区| 陆川县| 元阳县| 绥芬河市| 旅游| 池州市| 榆林市| 龙井市| 磐安县| 全州县| 株洲县| 安龙县| 增城市| 宜君县| 康乐县| 宁安市| 房山区| 府谷县| 开封县| 民和| 东辽县| 建始县| 石家庄市| 雷山县| 昌邑市| 英德市| 崇礼县| 丹巴县| 县级市| 嘉义市| 离岛区| 治多县| 和田县| 纳雍县|