在Windows 8中我們的粘貼板分別儲存4種資訊:文本、圖片、網頁、檔案。在本文中我們將分別複製和粘 貼這4種元素,當然你也可以在外部複製這4種元素,然後在程式中粘貼出來。
DataPackage:包含使用者 希望與另一個應用程式交換的資料
//設定一個中轉變數儲存使用者的值 DataPackage dp = new DataPackage();
第一:我們來看看複製和粘貼文本的幕後處理代碼 。
//<!--複製文本--> private void CopyText_Click(object sender, RoutedEventArgs e) { dp.SetText(this.SourceText.Text); Clipboard.SetContent(dp); } //<!--粘貼文本--> private async void PasteText_Click(object sender, RoutedEventArgs e) { var ClipBoardData = Clipboard.GetContent(); if (ClipBoardData.Contains(StandardDataFormats.Text)) { this.TargetText.Text = await ClipBoardData.GetTextAsync(); } }
第二:複製和粘貼圖片幕後處理代碼
//<!--複製圖片--> private async void CopyImage_Click(object sender, RoutedEventArgs e) { Uri uri = new Uri("ms-appx:///Assets/iphone0426_006.jpg"); StorageFile file = await StorageFile.GetFileFromApplicationUriAsync(uri); dp.SetBitmap(RandomAccessStreamReference.CreateFromFile(file)); Clipboard.SetContent(dp); } //<!--粘貼圖片--> private async void PasteImage_Click(object sender, RoutedEventArgs e) { var ClipBoardData = Clipboard.GetContent(); if (ClipBoardData.Contains(StandardDataFormats.Bitmap)) { RandomAccessStreamReference img = await ClipBoardData.GetBitmapAsync(); var imgstream = await img.OpenReadAsync(); BitmapImage bitmap = new BitmapImage(); bitmap.SetSource(imgstream); this.TargetImage.Source = bitmap; } }
第三:複製和粘貼HTML的幕後處理代碼
//<!--複製HTML--> private void CopyHtml_Click(object sender, RoutedEventArgs e) { string html = HtmlFormatHelper.CreateHtmlFormat(this.SourceHtml.InvokeScript("eval", new string[] { "document.documentElement.outerHTML;" })); dp.SetHtmlFormat(html); Clipboard.SetContent(dp); } //<!--粘貼HTML--> private async void PasteHtml_Click(object sender, RoutedEventArgs e) { var ClipBoardData = Clipboard.GetContent(); if (ClipBoardData.Contains(StandardDataFormats.Html)) { string html = await ClipBoardData.GetHtmlFormatAsync(); this.TargetHtml.NavigateToString(html); } }
第四:複製和粘貼檔案的幕後處理代碼
//<!--複製檔案--> private async void CopyFile_Click(object sender, RoutedEventArgs e) { Uri uri1 = new Uri("ms-appx:///Assets/iphone0426_006.jpg"); StorageFile file1 = await StorageFile.GetFileFromApplicationUriAsync(uri1); Uri uri2 = new Uri("ms-appx:///Assets/iphone0426_010.jpg"); StorageFile file2 = await StorageFile.GetFileFromApplicationUriAsync(uri2); List<StorageFile> filelist = new List<StorageFile>(); filelist.Add(file1); filelist.Add(file2); dp.SetStorageItems(filelist); Clipboard.SetContent(dp); } //<!--粘貼檔案--> private async void PasteFile_Click(object sender, RoutedEventArgs e) { var ClipBoardData = Clipboard.GetContent(); this.TargetFile.Text = ""; if (ClipBoardData.Contains(StandardDataFormats.StorageItems)) { var filelist = await ClipBoardData.GetStorageItemsAsync(); foreach (StorageFile sfile in filelist) { StorageFile storageFileCopy = await sfile.CopyAsync(KnownFolders.DocumentsLibrary, sfile.Name,NameCollisionOption.ReplaceExisting); this.TargetFile.Text += sfile.Name + "檔案粘貼一份到“庫\\文檔\\" + sfile.Name+"\r"; } } }