[源码下载]

重新想象 Windows 8 Store Apps (40) - 剪切板: 复制/粘贴文本, html, 图片, 文件

作者:webabcd

介绍
重新想象 Windows 8 Store Apps 之 剪切板

  • Clipboard - 剪切板
  • 复制/粘贴文本
  • 复制/粘贴html
  • 复制/粘贴图片
  • 复制/粘贴文件

示例
1、演示剪切板的基本应用
Clipboard/Demo.xaml

<Page
x:Class="XamlDemo.Clipboard.Demo"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:XamlDemo.Clipboard"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"> <Grid Background="Transparent">
<StackPanel Margin="120 0 0 0"> <TextBlock Name="lblMsg" FontSize="14.667" /> <Button Name="btnCopyText" Content="复制一段文本到剪切板" Click="btnCopyText_Click_1" Margin="0 10 0 0" /> <Button Name="btnPasteText" Content="粘贴剪切板中的文本" Click="btnPasteText_Click_1" Margin="0 10 0 0" /> <Button Name="btnShowAvailableFormats" Content="获取剪切板中包含的数据的格式类型" Click="btnShowAvailableFormats_Click_1" Margin="0 10 0 0" /> <Button Name="btnClear" Content="清除剪切板中的全部内容" Click="btnClear_Click_1" Margin="0 10 0 0" /> </StackPanel>
</Grid>
</Page>

Clipboard/Demo.xaml.cs

/*
* Clipboard - 剪切板
* SetContent() - 将指定的 DataPackage 存入剪切板
* GetContent() - 从剪切板中获取 DataPackage 对象
* Clear() - 清除剪切板中的全部数据
* Flush() - 正常情况下,关闭 app 后,此 app 保存到剪切板的数据就会消失;调用此方法后,即使关闭 app,剪切板中的数据也不会消失
* ContentChanged - 剪切板中的数据发生变化时所触发的事件
*
* DataPackage - 用于封装 Clipboard 或 ShareContract 的数据(详细说明见 ShareContract 的 Demo)
* SetText(), SetUri(), SetHtmlFormat(), SetRtf(), SetBitmap(), SetStorageItems(), SetData(), SetDataProvider() - 设置复制到剪切板的各种格式的数据(注:一个 DataPackage 可以有多种不同格式的数据)
* RequestedOperation - 操作类型(DataPackageOperation 枚举: None, Copy, Move, Link),没发现此属性有任何作用
*
* DataPackageView - DataPackage 对象的只读版本,从剪切板获取数据或者共享目标接收数据均通过此对象来获取 DataPackage 对象的数据(详细说明见 ShareContract 的 Demo)
*/ using System;
using Windows.ApplicationModel.DataTransfer;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation; namespace XamlDemo.Clipboard
{
public sealed partial class Demo : Page
{
public Demo()
{
this.InitializeComponent();
} protected override void OnNavigatedTo(NavigationEventArgs e)
{
Windows.ApplicationModel.DataTransfer.Clipboard.ContentChanged += Clipboard_ContentChanged;
} protected override void OnNavigatedFrom(NavigationEventArgs e)
{
Windows.ApplicationModel.DataTransfer.Clipboard.ContentChanged -= Clipboard_ContentChanged;
} void Clipboard_ContentChanged(object sender, object e)
{
lblMsg.Text += Environment.NewLine;
lblMsg.Text += "剪切板中的内容发生了变化";
} // 复制一段文本到剪切板
private void btnCopyText_Click_1(object sender, RoutedEventArgs e)
{
// 构造保存到剪切板的 DataPackage 对象
DataPackage dataPackage = new DataPackage();
dataPackage.SetText("I am webabcd: " + DateTime.Now.ToString()); try
{
Windows.ApplicationModel.DataTransfer.Clipboard.SetContent(dataPackage); // 保存 DataPackage 对象到剪切板
Windows.ApplicationModel.DataTransfer.Clipboard.Flush(); // 当此 app 关闭后,依然保留剪切板中的数据
lblMsg.Text = "已将内容复制到剪切板";
}
catch (Exception ex)
{
lblMsg.Text = ex.ToString();
}
} // 显示剪切板中的文本数据
private async void btnPasteText_Click_1(object sender, RoutedEventArgs e)
{
// 获取剪切板中的数据
DataPackageView dataPackageView = Windows.ApplicationModel.DataTransfer.Clipboard.GetContent(); // 如果剪切板中有文本数据,则获取并显示该文本
if (dataPackageView.Contains(StandardDataFormats.Text))
{
try
{
string text = await dataPackageView.GetTextAsync();
lblMsg.Text = text;
}
catch (Exception ex)
{
lblMsg.Text = ex.ToString();
}
}
else
{
lblMsg.Text = "剪切板中无文本内容";
}
} // 显示剪切板中包含的数据的格式类型,可能会有 StandardDataFormats 枚举的格式,也可能会有自定义的格式(关于自定义格式可以参见:ShareContract 的 Demo)
private void btnShowAvailableFormats_Click_1(object sender, RoutedEventArgs e)
{
DataPackageView dataPackageView = Windows.ApplicationModel.DataTransfer.Clipboard.GetContent();
if (dataPackageView != null && dataPackageView.AvailableFormats.Count > )
{
var availableFormats = dataPackageView.AvailableFormats.GetEnumerator();
while (availableFormats.MoveNext())
{
lblMsg.Text += Environment.NewLine;
lblMsg.Text += availableFormats.Current;
}
}
else
{
lblMsg.Text = "剪切板中无任何内容";
}
} // 清除剪切板中的全部数据
private void btnClear_Click_1(object sender, RoutedEventArgs e)
{
Windows.ApplicationModel.DataTransfer.Clipboard.Clear();
}
}
}

2、演示如何复制 html 数据到剪切板,以及如何从剪切板中获取 html 数据 
Clipboard/CopyHtml.xaml

<Page
x:Class="XamlDemo.Clipboard.CopyHtml"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:XamlDemo.Clipboard"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"> <Grid Background="Transparent">
<StackPanel Margin="120 0 0 0"> <TextBlock Name="lblMsg" FontSize="14.667" /> <Button Name="btnCopyHtml" Content="复制一段 html 到剪切板" Click="btnCopyHtml_Click_1" Margin="0 10 0 0" /> <Button Name="btnPasteHtml" Content="粘贴剪切板中的 html" Click="btnPasteHtml_Click_1" Margin="0 10 0 0" /> </StackPanel>
</Grid>
</Page>

Clipboard/CopyHtml.xaml.cs

/*
* 演示如何复制 html 数据到剪切板,以及如何从剪切板中获取 html 数据
*
* HtmlFormatHelper - 在 Clipboard 中传递 html 数据或在 ShareContract 中传递 html 数据时的帮助类
* CreateHtmlFormat() - 封装需要传递的 html 字符串,以便以 html 方式传递数据
* GetStaticFragment() - 解封装传递过来的经过封装的 html 数据,从而获取初始需要传递的 html 字符串
*/ using System;
using Windows.ApplicationModel.DataTransfer;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls; namespace XamlDemo.Clipboard
{
public sealed partial class CopyHtml : Page
{
public CopyHtml()
{
this.InitializeComponent();
} // 复制 html 字符串到剪切板
private void btnCopyHtml_Click_1(object sender, RoutedEventArgs e)
{
DataPackage dataPackage = new DataPackage();
// 封装一下需要复制的 html 数据,以便以 html 的方式将数据复制到剪切板
string htmlFormat = HtmlFormatHelper.CreateHtmlFormat("<body>I am webabcd</body>");
dataPackage.SetHtmlFormat(htmlFormat); try
{
Windows.ApplicationModel.DataTransfer.Clipboard.SetContent(dataPackage);
lblMsg.Text = "已将内容复制到剪切板";
}
catch (Exception ex)
{
lblMsg.Text = ex.ToString();
}
} // 显示剪切板中的 html 数据
private async void btnPasteHtml_Click_1(object sender, RoutedEventArgs e)
{
DataPackageView dataPackageView = Windows.ApplicationModel.DataTransfer.Clipboard.GetContent(); if (dataPackageView.Contains(StandardDataFormats.Html))
{
try
{
// 封装后的数据
string htmlFormat = await dataPackageView.GetHtmlFormatAsync();
// 封装前的数据
string htmlFragment = HtmlFormatHelper.GetStaticFragment(htmlFormat); lblMsg.Text = "htmlFormat(封装后的数据): ";
lblMsg.Text += Environment.NewLine;
lblMsg.Text += htmlFormat;
lblMsg.Text += Environment.NewLine;
lblMsg.Text += Environment.NewLine;
lblMsg.Text += "htmlFragment(封装前的数据): ";
lblMsg.Text += Environment.NewLine;
lblMsg.Text += htmlFragment;
}
catch (Exception ex)
{
lblMsg.Text = ex.ToString();
}
}
else
{
lblMsg.Text = "剪切板中无 html 内容";
}
}
}
}

3、演示如何复制图片内容剪切板,以及如何从剪切板中获取图片内容,以及数据的延迟复制
Clipboard/CopyImage.xaml

<Page
x:Class="XamlDemo.Clipboard.CopyImage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:XamlDemo.Clipboard"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"> <Grid Background="Transparent">
<StackPanel Margin="120 0 0 0"> <TextBlock Name="lblMsg" FontSize="14.667" />
<Image Name="imgBitmap" Stretch="None" HorizontalAlignment="Left" Margin="0 10 0 0" /> <Button Name="btnCopyImage" Content="复制图片内容到剪切板" Click="btnCopyImage_Click_1" Margin="0 10 0 0" /> <Button Name="btnCopyImageWithDeferral" Content="复制数据提供器到剪切板,当“粘贴”操作被触发时由数据提供器生成用于粘贴的图片数据" Click="btnCopyImageWithDeferral_Click_1" Margin="0 10 0 0" /> <Button Name="btnPasteImage" Content="粘贴剪切板中的图片内容" Click="btnPasteImage_Click_1" Margin="0 10 0 0" /> </StackPanel>
</Grid>
</Page>

Clipboard/CopyImage.xaml.cs

/*
* 1、演示如何复制图片内容剪切板,以及如何从剪切板中获取图片内容
* 2、演示如何通过 SetDataProvider() 延迟数据的复制,即在“粘贴”操作触发后由数据提供器生成相关数据
*/ using System;
using Windows.ApplicationModel.DataTransfer;
using Windows.Graphics.Imaging;
using Windows.Storage;
using Windows.Storage.Streams;
using Windows.UI.Core;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Media.Imaging; namespace XamlDemo.Clipboard
{
public sealed partial class CopyImage : Page
{
public CopyImage()
{
this.InitializeComponent();
} // 复制图片内容到剪切板
private void btnCopyImage_Click_1(object sender, RoutedEventArgs e)
{
DataPackage dataPackage = new DataPackage();
dataPackage.SetBitmap(RandomAccessStreamReference.CreateFromUri(new Uri("ms-appx:///Assets/Logo.png", UriKind.Absolute))); try
{
Windows.ApplicationModel.DataTransfer.Clipboard.SetContent(dataPackage);
lblMsg.Text = "已将内容复制到剪切板";
}
catch (Exception ex)
{
lblMsg.Text = ex.ToString();
}
} // 延迟复制
private async void btnCopyImageWithDeferral_Click_1(object sender, RoutedEventArgs e)
{
StorageFile imageFile = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///Assets/Logo.png", UriKind.Absolute)); DataPackage dataPackage = new DataPackage();
dataPackage.SetDataProvider(StandardDataFormats.Bitmap, async (request) =>
{
/*
* 当从剪切板中获取 StandardDataFormats.Bitmap 数据时,会执行到此处以提供相关数据
*/ if (imageFile != null)
{
// 开始异步处理
var deferral = request.GetDeferral(); try
{
using (var imageStream = await imageFile.OpenAsync(FileAccessMode.Read))
{
// 将图片缩小一倍
BitmapDecoder imageDecoder = await BitmapDecoder.CreateAsync(imageStream);
var inMemoryStream = new InMemoryRandomAccessStream();
var imageEncoder = await BitmapEncoder.CreateForTranscodingAsync(inMemoryStream, imageDecoder);
imageEncoder.BitmapTransform.ScaledWidth = (uint)(imageDecoder.OrientedPixelWidth * 0.5);
imageEncoder.BitmapTransform.ScaledHeight = (uint)(imageDecoder.OrientedPixelHeight * 0.5);
await imageEncoder.FlushAsync(); // 指定需要复制到剪切板的数据
request.SetData(RandomAccessStreamReference.CreateFromStream(inMemoryStream)); await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
lblMsg.Text = "数据已生成";
});
}
}
finally
{
// 通知系统已完成异步操作
deferral.Complete();
}
}
}); try
{
Windows.ApplicationModel.DataTransfer.Clipboard.SetContent(dataPackage);
lblMsg.Text = "已将数据提供器复制到剪切板,在“粘贴”操作时才会生成数据";
}
catch (Exception ex)
{
lblMsg.Text = ex.ToString();
}
} // 显示剪切板中的图片内容
private async void btnPasteImage_Click_1(object sender, RoutedEventArgs e)
{
DataPackageView dataPackageView = Windows.ApplicationModel.DataTransfer.Clipboard.GetContent(); if (dataPackageView.Contains(StandardDataFormats.Bitmap))
{
try
{
IRandomAccessStreamReference randomStream = await dataPackageView.GetBitmapAsync();
if (randomStream != null)
{
using (IRandomAccessStreamWithContentType imageStream = await randomStream.OpenReadAsync())
{
BitmapImage bitmapImage = new BitmapImage();
bitmapImage.SetSource(imageStream);
imgBitmap.Source = bitmapImage;
}
}
}
catch (Exception ex)
{
lblMsg.Text = ex.ToString();
}
}
else
{
lblMsg.Text = "剪切板中无 bitmap 内容";
}
}
}
}

4、演示如何复制指定的文件到剪切板,以及如何从剪切板中获取文件并保存到指定的路径
Clipboard/CopyFile.xaml

<Page
x:Class="XamlDemo.Clipboard.CopyFile"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:XamlDemo.Clipboard"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"> <Grid Background="Transparent">
<StackPanel Margin="120 0 0 0"> <TextBlock Name="lblMsg" FontSize="14.667" TextWrapping="Wrap" Margin="0 0 10 0" /> <Button Name="btnCopyFile" Content="复制一个文件到剪切板" Click="btnCopyFile_Click_1" Margin="0 10 0 0" /> <Button Name="btnPasteFile" Content="粘贴剪切板中的文件到指定的路径" Click="btnPasteFile_Click_1" Margin="0 10 0 0" /> </StackPanel>
</Grid>
</Page>

Clipboard/CopyFile.xaml.cs

/*
* 演示如何复制指定的文件到剪切板,以及如何从剪切板中获取文件并保存到指定的路径
*/ using System;
using System.Linq;
using System.Collections.Generic;
using Windows.ApplicationModel.DataTransfer;
using Windows.Storage;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls; namespace XamlDemo.Clipboard
{
public sealed partial class CopyFile : Page
{
public CopyFile()
{
this.InitializeComponent();
} // 保存文件到剪切板
private async void btnCopyFile_Click_1(object sender, RoutedEventArgs e)
{
StorageFile file = await ApplicationData.Current.LocalFolder.CreateFileAsync(@"webabcdTest\clipboard.txt", CreationCollisionOption.ReplaceExisting);
await FileIO.WriteTextAsync(file, "I am webabcd: " + DateTime.Now.ToString()); DataPackage dataPackage = new DataPackage();
dataPackage.SetStorageItems(new List<StorageFile>() { file }); dataPackage.RequestedOperation = DataPackageOperation.Move;
try
{
Windows.ApplicationModel.DataTransfer.Clipboard.SetContent(dataPackage);
lblMsg.Text = "已将文件复制到剪切板";
}
catch (Exception ex)
{
lblMsg.Text = ex.ToString();
}
} // 从剪切板中获取文件并保存到指定的路径
private async void btnPasteFile_Click_1(object sender, RoutedEventArgs e)
{
DataPackageView dataPackageView = Windows.ApplicationModel.DataTransfer.Clipboard.GetContent(); if (dataPackageView.Contains(StandardDataFormats.StorageItems))
{
try
{
IReadOnlyList<IStorageItem> storageItems = await dataPackageView.GetStorageItemsAsync();
StorageFile file = storageItems.First() as StorageFile;
if (file != null)
{
StorageFile newFile = await file.CopyAsync(ApplicationData.Current.TemporaryFolder, file.Name, NameCollisionOption.ReplaceExisting);
if (newFile != null)
{
lblMsg.Text = string.Format("已将文件从{0}复制到{1}", file.Path, newFile.Path);
}
}
}
catch (Exception ex)
{
lblMsg.Text = ex.ToString();
}
}
else
{
lblMsg.Text = "剪切板中无 StorageItems 内容";
}
}
}
}

OK
[源码下载]

重新想象 Windows 8 Store Apps (40) - 剪切板: 复制/粘贴文本, html, 图片, 文件的更多相关文章

  1. 重新想象 Windows 8 Store Apps 系列文章索引

    [源码下载][重新想象 Windows 8.1 Store Apps 系列文章] 重新想象 Windows 8 Store Apps 系列文章索引 作者:webabcd 1.重新想象 Windows ...

  2. 重新想象 Windows 8 Store Apps (23) - 文件系统: 文本的读写, 二进制的读写, 流的读写, 最近访问列表和未来访问列表

    原文:重新想象 Windows 8 Store Apps (23) - 文件系统: 文本的读写, 二进制的读写, 流的读写, 最近访问列表和未来访问列表 [源码下载] 重新想象 Windows 8 S ...

  3. 重新想象 Windows 8 Store Apps (37) - 契约: Settings Contract

    [源码下载] 重新想象 Windows 8 Store Apps (37) - 契约: Settings Contract 作者:webabcd 介绍重新想象 Windows 8 Store Apps ...

  4. 重新想象 Windows 8 Store Apps (39) - 契约: Share Contract

    [源码下载] 重新想象 Windows 8 Store Apps (39) - 契约: Share Contract 作者:webabcd 介绍重新想象 Windows 8 Store Apps 之  ...

  5. 重新想象 Windows 8 Store Apps (51) - 输入: 涂鸦板

    [源码下载] 重新想象 Windows 8 Store Apps (51) - 输入: 涂鸦板 作者:webabcd 介绍重新想象 Windows 8 Store Apps 之 涂鸦板 通过 Poin ...

  6. 重新想象 Windows 8 Store Apps (12) - 控件之 GridView 特性: 拖动项, 项尺寸可变, 分组显示

    原文:重新想象 Windows 8 Store Apps (12) - 控件之 GridView 特性: 拖动项, 项尺寸可变, 分组显示 [源码下载] 重新想象 Windows 8 Store Ap ...

  7. 重新想象 Windows 8 Store Apps (8) - 控件之 WebView

    原文:重新想象 Windows 8 Store Apps (8) - 控件之 WebView [源码下载] 重新想象 Windows 8 Store Apps (8) - 控件之 WebView 作者 ...

  8. 重新想象 Windows 8 Store Apps (5) - 控件之集合控件: ComboBox, ListBox, FlipView, ItemsControl, ItemsPresenter

    原文:重新想象 Windows 8 Store Apps (5) - 控件之集合控件: ComboBox, ListBox, FlipView, ItemsControl, ItemsPresente ...

  9. 重新想象 Windows 8 Store Apps (34) - 通知: Toast Demo, Tile Demo, Badge Demo

    [源码下载] 重新想象 Windows 8 Store Apps (34) - 通知: Toast Demo, Tile Demo, Badge Demo 作者:webabcd 介绍重新想象 Wind ...

随机推荐

  1. 在 Excel 中使用公式拆分字符串日期

    如图所示,分别使用 LEFT.MIDB.RIGHT 来拆分再拼接字符串即可: =LEFT(A1,4)&"-"&MIDB(A1,5,2)&"-&qu ...

  2. 迁移SQL SERVER 数据库实例

    由于某些原因,需要将2个数据库实例合并为1个,也就是说要把其中的一台迁移到另外一台上面. 背景介绍 :下面的B,C代表2个实例,要把B中相关东西迁移到C实例上面.其中B上面有一部分的同步是从另外一台服 ...

  3. Windows内核安全与驱动开发

    这篇是计算机中Windows Mobile/Symbian类的优质预售推荐<Windows内核安全与驱动开发>. 编辑推荐 本书适合计算机安全软件从业人员.计算机相关专业院校学生以及有一定 ...

  4. 《热血传奇2》wix、wil文件解析Java实现

    在百度上搜索java+wil只有iteye上一篇有丁点儿内容,不过他说的是错的!或者说是不完整的,我个人认为我对于热血传奇客户端解析还是有一定研究的,请移步: <JMir——Java版热血传奇2 ...

  5. Spark源码系列(二)RDD详解

    1.什么是RDD? 上一章讲了Spark提交作业的过程,这一章我们要讲RDD.简单的讲,RDD就是Spark的input,知道input是啥吧,就是输入的数据. RDD的全名是Resilient Di ...

  6. C# 实现字符串去重

    方法一 注:需要.net 3.5框架的支持 string s = "101,102,103,104,105,101,102,103,104,105,106,107,101,108" ...

  7. [PaPaPa][需求说明书][V0.1]

    PaPaPa软件需求说明书V0.1 前   言 我觉得我们废话不能多,废话一多的话大家就找不到重点了,其实本项目是出于技术研究的目的来开发的,大家讨论了半天决定要做社(yue)交(pao)类的项目. ...

  8. FFmpeg编译出错_img_convert 找不到

    问题出现在下载的ffmpeg的版本不一样,在0.4.8以前的版本中还有img_convert这个函数,新版本中用sws_getContext和sws_scale代替了.简单说明如下: 新版本的ffmp ...

  9. 通过RFC给SAP新建用户

    1.首先引用dll,然后在程序开头:using SAP.Middleware.Connector; 2.接下去就是设置登陆参数了,以前相关博文都有说明: public class MyBackendC ...

  10. RESTful 良好的API设计风格

    1.使用名词而不是动词 Resource资源 GET读 POST创建 PUT修改 DELETE /cars 返回 cars集合 创建新的资源 批量更新cars 删除所有cars /cars/711 返 ...