public void Copy() { try { if (_share.Data.Properties.ApplicationName != Constants.ApplicationName) { _share.ReportSubmittedBackgroundTask(); var content = new DataPackage(); _values.CopyTo(content); Windows.ApplicationModel.DataTransfer.Clipboard.SetContent(content); Windows.ApplicationModel.DataTransfer.Clipboard.Flush(); Windows.ApplicationModel.DataTransfer.Clipboard.ContentChanged += OnClipboardContentChanged; _share.DismissUI(); } else { _share.ReportCompleted(); } } catch (Exception ex) { _share.ReportError(ex.Message); } }
private void CopyLink() { DataPackage dataPackage = new DataPackage(); dataPackage.RequestedOperation = DataPackageOperation.Copy; dataPackage.SetText(GetLinkToShare()); Clipboard.SetContent(dataPackage); }
private void Copy_Click(object sender, RoutedEventArgs e) { DataPackage data = new DataPackage(); data.SetText(tbInput.Text); Clipboard.SetContent(data); }
public void SetText(string text) { var dp = new DataPackage(); dp.SetText(text); Clipboard.SetContent(dp); UWPUtilities.GiveStatusBarFeedback("Copied to clipboard..."); }
void CopyButton_Click(object sender, RoutedEventArgs e) { OutputText.Text = ""; OutputResourceMapKeys.Text = ""; OutputHtml.NavigateToString("<HTML></HTML>"); // Set the content to DataPackage as html format string htmlFormat = HtmlFormatHelper.CreateHtmlFormat(this.htmlFragment); var dataPackage = new DataPackage(); dataPackage.SetHtmlFormat(htmlFormat); // Set the content to DataPackage as (plain) text format string plainText = HtmlUtilities.ConvertToText(this.htmlFragment); dataPackage.SetText(plainText); // Populate resourceMap with StreamReference objects corresponding to local image files embedded in HTML var imgUri = new Uri(imgSrc); var imgRef = RandomAccessStreamReference.CreateFromUri(imgUri); dataPackage.ResourceMap[imgSrc] = imgRef; try { // Set the DataPackage to clipboard. Windows.ApplicationModel.DataTransfer.Clipboard.SetContent(dataPackage); OutputText.Text = "Text and HTML formats have been copied to clipboard. "; } catch (Exception ex) { // Copying data to Clipboard can potentially fail - for example, if another application is holding Clipboard open rootPage.NotifyUser("Error copying content to Clipboard: " + ex.Message + ". Try again", NotifyType.ErrorMessage); } }
async void CopyButton_Click(object sender, RoutedEventArgs e) { OutputText.Text = "Storage Items: "; var filePicker = new FileOpenPicker { ViewMode = PickerViewMode.List, FileTypeFilter = { "*" } }; var storageItems = await filePicker.PickMultipleFilesAsync(); if (storageItems.Count > 0) { OutputText.Text += storageItems.Count + " file(s) are copied into clipboard"; var dataPackage = new DataPackage(); dataPackage.SetStorageItems(storageItems); // Request a copy operation from targets that support different file operations, like File Explorer dataPackage.RequestedOperation = DataPackageOperation.Copy; try { Windows.ApplicationModel.DataTransfer.Clipboard.SetContent(dataPackage); } catch (Exception ex) { // Copying data to Clipboard can potentially fail - for example, if another application is holding Clipboard open rootPage.NotifyUser("Error copying content to Clipboard: " + ex.Message + ". Try again", NotifyType.ErrorMessage); } } else { OutputText.Text += "No file was selected."; } }
private void Clipboard_Click(object sender, RoutedEventArgs e) { var dataPackage = new DataPackage(); dataPackage.SetText(Match.AudioUrl); Clipboard.SetContent(dataPackage); }
private void Transfer_DataRequested(DataTransferManager sender, DataRequestedEventArgs args) { if (!Equals(null, VM)) { DataPackage dp = new DataPackage(); switch (VM.GetType().Name) { case "PictureViewModel": dp.Properties.Title = "分享图片"; dp.SetText( $"一张图片,千言万语[来自ONE-UWP的分享]:{(VM as PictureViewModel).Picture.WebLk}"); break; case "ArticleViewModel": dp.Properties.Title = "分享文章"; dp.SetText($"世间风情,字里行间[来自ONE-UWP的分享]:{(VM as ArticleViewModel).Article.WebLk}"); break; case "QuestionViewModel": dp.Properties.Title = "分享问题"; dp.SetText($"每天一问,有问必答[来自ONE-UWP的分享]:{(VM as QuestionViewModel).Question.WebLk}"); break; case "ThingViewModel": dp.Properties.Title = "分享东西"; dp.SetText($"友好世界,有好东西[来自ONE-UWP的分享]:{(VM as ThingViewModel).Thing.Wu}"); break; } args.Request.Data = dp; } else { return; } }
/// <summary> /// Invoked when this page is about to be displayed in a Frame. /// </summary> /// <param name="e">Event data that describes how this page was reached. The Parameter /// property is typically used to configure the page.</param> protected override void OnNavigatedTo(NavigationEventArgs e) { XNamespace p_ns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation"; XNamespace xaml_ns = "http://schemas.microsoft.com/winfx/2006/xaml"; var doc = XDocument.Load(@"Common\StandardStyles.xaml"); foreach (var style in doc.Descendants(p_ns + "Style")) { var key = style.Attribute(xaml_ns + "Key"); if (key != null && key.Value != null) { var basedOn = style.Attribute("BasedOn"); if (basedOn != null && basedOn.Value == @"{StaticResource AppBarButtonStyle}") { var button = new Button(); button.Style = App.Current.Resources[key.Value] as Style; ToolTipService.SetToolTip(button, key.Value); button.Click += (sender, args) => { string styleName = ToolTipService.GetToolTip(sender as Button) as string; DataPackage clipboardData = new DataPackage(); clipboardData.SetText(styleName); Clipboard.SetContent(clipboardData); }; AppBarButtonListView.Items.Add(button); } } } }
private async void Grid_DoubleTapped(object sender, DoubleTappedRoutedEventArgs e) { Grid grid = (Grid)sender; Records.Items items = (Records.Items)grid.DataContext; String Data = String.Empty; ResourceLoader resourceLoader = new ResourceLoader(); Data += String.Format(resourceLoader.GetString("pageResult_Assignment") + Environment.NewLine, items.Oid); Data += String.Format(resourceLoader.GetString("pageResult_Registry") + Environment.NewLine, items.RegistryID); Data += String.Format(resourceLoader.GetString("pageResult_OrganizationName") + Environment.NewLine, items.Name); Data += String.Format(resourceLoader.GetString("pageResult_OrganizationAddress") + Environment.NewLine, items.Address); if ( (items.Protocol != String.Empty) && (items.Protocol != null)) { Data += String.Format(resourceLoader.GetString("pageResult_Protocol") + Environment.NewLine, items.Protocol); } DataPackage dataPackage = new DataPackage(); dataPackage.SetText(Data); Clipboard.SetContent(dataPackage); MessageDialog msgbox = new MessageDialog(Data, resourceLoader.GetString("pageResult_DialogCopied")); msgbox.Commands.Clear(); msgbox.Commands.Add(new UICommand { Label = resourceLoader.GetString("pageResult_DialogClose"), Id = 0 }); var res = await msgbox.ShowAsync(); }
// копирование ссылки private void CopyPageLink(object sender, object e) { Windows.ApplicationModel.DataTransfer.DataPackage dataPackage = new Windows.ApplicationModel.DataTransfer.DataPackage(); dataPackage.SetText(App.Settings.current_site + ((sender as AppBarButton).DataContext as string)); Windows.ApplicationModel.DataTransfer.Clipboard.SetContent(dataPackage); ShowMessage("Сopied!"); }
private void CopyButtonTapped(object sender, TappedRoutedEventArgs e) { var dataPackage = new DataPackage(); dataPackage.SetText(this.tbCurrent.Text); Clipboard.SetContent(dataPackage); this.tbCopyed.Visibility = Visibility.Visible; }
public ShareRequestAdapter(DataRequest dataRequest, Guid id) { _dataRequest = dataRequest; _data = _dataRequest.Data; _properties = _data.Properties; _properties.ApplicationName = "ExampleApplication.WinRT"; Id = id; }
private void btn_Share_Click(object sender, RoutedEventArgs e) { Windows.ApplicationModel.DataTransfer.DataPackage pack = new Windows.ApplicationModel.DataTransfer.DataPackage(); pack.SetText(string.Format("我正在哔哩哔哩上看《{0}》\r\n地址:http://www.bilibili.com/video/av{1}", (this.DataContext as VideoInfoModels).title, _aid)); Windows.ApplicationModel.DataTransfer.Clipboard.SetContent(pack); // 保存 DataPackage 对象到剪切板 Windows.ApplicationModel.DataTransfer.Clipboard.Flush(); messShow.Show("已将内容复制到剪切板", 3000); }
private void Copybutton_Tapped(object sender, TappedRoutedEventArgs e) { var dataPackage = new DataPackage(); string plainText = HtmlUtilities.ConvertToText(output.Text); dataPackage.SetText(plainText); Windows.ApplicationModel.DataTransfer.Clipboard.SetContent(dataPackage); }
private void OnDataRequested(DataTransferManager sender, DataRequestedEventArgs e) { _requestData = e.Request.Data; _requestData.Properties.Title = _title; _requestData.Properties.Description = _description; _requestData.SetWebLink(new Uri(_imageUrl)); }
private void Share_Click(object sender, RoutedEventArgs e) { Windows.ApplicationModel.DataTransfer.DataPackage pack = new Windows.ApplicationModel.DataTransfer.DataPackage(); pack.SetText(string.Format("我正在BiliBili追{0},一起来看吧\r\n地址:http://bangumi.bilibili.com/anime/{1}", txt_Name.Text, banID)); Windows.ApplicationModel.DataTransfer.Clipboard.SetContent(pack); // 保存 DataPackage 对象到剪切板 Windows.ApplicationModel.DataTransfer.Clipboard.Flush(); messShow.Show("已将内容复制到剪切板", 3000); }
private static void TextBlock_Tapped1(object sender, TappedRoutedEventArgs e) { // Use this to copy field value to Clipboard, if using TextBlock var textb = sender as TextBlock; var dataPackage = new DataPackage(); dataPackage.SetText(textb.Text); Clipboard.SetContent(dataPackage); }
private void CopyImage_Click(object sender, RoutedEventArgs e) { var data = new DataPackage(); var bi = FirstImage.Source as BitmapImage; var uri = bi.UriSource; data.SetBitmap(RandomAccessStreamReference.CreateFromUri(uri)); Clipboard.SetContent(data); }
private void CopyToClipBoard(object sender, RoutedEventArgs e) { var content = new DataPackage(); content.SetUri(new Uri(textboxLink.Text)); content.SetText(textboxLink.Text); Clipboard.SetContent(content); }
private void Button_Click_1(object sender, RoutedEventArgs e) { DataPackage dataPackage = new DataPackage(); dataPackage.RequestedOperation = DataPackageOperation.Copy; dataPackage.SetText("クリップボードに文字列を渡します!!"); Clipboard.SetContent(dataPackage); }
private void cd_PrimaryButtonClick(ContentDialog sender, ContentDialogButtonClickEventArgs args) { Windows.ApplicationModel.DataTransfer.DataPackage pack = new Windows.ApplicationModel.DataTransfer.DataPackage(); pack.SetText((sender.DataContext as LiveVideoModel).item.share_url); Windows.ApplicationModel.DataTransfer.Clipboard.SetContent(pack); // 保存 DataPackage 对象到剪切板 Windows.ApplicationModel.DataTransfer.Clipboard.Flush(); messShow.Show("已将内容复制到剪切板", 3000); }
private void menu_copy_Click(object sender, RoutedEventArgs e) { DataPackage pack = new Windows.ApplicationModel.DataTransfer.DataPackage(); pack.SetText(webView.Source.AbsoluteUri); Clipboard.SetContent(pack); // 保存 DataPackage 对象到剪切板 Clipboard.Flush(); }
private void ContentDialog_PrimaryButtonClick(ContentDialog sender, ContentDialogButtonClickEventArgs args) { var dataPackage = new DataPackage(); dataPackage.SetText(Result); Clipboard.SetContent(dataPackage); MessageHelper.ShowToastNotification("StoreLogo.png", "已复制到粘贴板!", NotificationAudioNames.Default); args.Cancel = true; }
public void Properties_Title_SettingValueThrowsException() { DataPackage dataPackage = new DataPackage(); SharePackageView sharePackage = new SharePackageView(dataPackage.GetView()); var e = Assert.Throws<InvalidOperationException>(() => sharePackage.Properties.Description = "Test Value"); Assert.Equal("Cannot modify share properties as a share target.", e.Message); }
public void Properties_Title_GetsValueFromDataPackageView() { DataPackage dataPackage = new DataPackage(); dataPackage.Properties.Title = "Test Value"; SharePackageView sharePackage = new SharePackageView(dataPackage.GetView()); Assert.Equal("Test Value", sharePackage.Properties.Title); }
public void Properties_Description_GetsValueFromDataPackageView() { DataPackage dataPackage = new DataPackage(); dataPackage.Properties.Description = "Test Value"; SharePackageView sharePackage = new SharePackageView(dataPackage.GetView()); Assert.Equal("Test Value", sharePackage.Properties.Description); }
public static void CopyToClipBoard(string str) { var dp = new DataPackage { RequestedOperation = DataPackageOperation.Copy, }; dp.SetText(str); Clipboard.SetContent(dp); }
/// <summary> /// 复制链接 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private async void ShareByCopyUriAppBarButton_Tapped(object sender, TappedRoutedEventArgs e) { DataPackage dataPackage = new DataPackage(); dataPackage.SetText(this._url); Clipboard.SetContent(dataPackage); MessageDialog messageDialog = new MessageDialog("复制成功"); IUICommand uiCommand = await messageDialog.ShowAsync(); this.Hide(); }
private void CharButton_Click(object sender, RoutedEventArgs e) { if (FontChar != null) { var dataPackage = new DataPackage(); dataPackage.SetText(FontChar.Char.ToString()); Clipboard.SetContent(dataPackage); } }
private async void CopyLinkToClipboardCommand(object sender, RoutedEventArgs e) { FlyoutMore.Hide(); var dp = new DataPackage(); dp.SetText($"http://www.myanimelist.net/{(ViewModel.AnimeMode ? "anime" : "manga")}/{ViewModel.Id}"); Clipboard.SetContent(dp); FlyoutMore.Hide(); UWPUtilities.GiveStatusBarFeedback("Copied to clipboard..."); }
public async Task SetData_SetsDataOnDataPackage() { DataPackage dataPackage = new DataPackage(); SharePackage sharePackage = new SharePackage(dataPackage); sharePackage.SetData<string>("Test Format", "Test Value"); object data = await dataPackage.GetView().GetDataAsync("Test Format"); Assert.Equal("Test Value", data); }
public void Contains_ReturnsTrueIfFormatIsAvailable() { DataPackage dataPackage = new DataPackage(); dataPackage.SetData("Format A", "Some data"); dataPackage.SetData("Format B", "Some data"); SharePackageView sharePackage = new SharePackageView(dataPackage.GetView()); Assert.True(sharePackage.Contains("Format A")); }
public void SetData_ThrowsException_IfFormatIdIsEmpty() { DataPackage dataPackage = new DataPackage(); SharePackage sharePackage = new SharePackage(dataPackage); var e = Assert.Throws<ArgumentException>(() => sharePackage.SetData<string>("", "Test Value")); Assert.Equal("The argument cannot be null or an empty string.\r\nParameter name: formatId", e.Message); Assert.Equal("formatId", e.ParamName); }
partial void HandleShareRequested(string shareLink) { var dataPackage = new DataPackage(); dataPackage.SetText(shareLink); dataPackage.SetWebLink(new Uri(shareLink)); Clipboard.SetContent(dataPackage); var notificationService = SimpleIoc.Default.GetInstance<NotificationService>(); notificationService.ShowToast("File shared", "A link has been copied to the clipboard", "Assets/Logo.scale-100.png"); this.Complete(); }
internal void SetText(string text) { if (string.IsNullOrWhiteSpace(text)) { return; } DT.DataPackage dataPackage = new DT.DataPackage(); dataPackage.SetText(text); DT.Clipboard.SetContent(dataPackage); }
public void setString(string text) { RunOnDispatcher(() => { if (text == null) { DataTransfer.Clipboard.Clear(); } else { var package = new DataTransfer.DataPackage(); package.SetData(DataTransfer.StandardDataFormats.Text, text); DataTransfer.Clipboard.SetContent(package); } }); }
internal static void SetToNativeClipboard(DataPackage content) { SetToNative(content, NSPasteboard.GeneralPasteboard); }
private static async Task <bool> ShowShareUIAsync(ShareUIOptions options, DataPackage dataPackage) { var rootViewController = UIApplication.SharedApplication?.KeyWindow?.RootViewController; if (rootViewController == null) { if (_instance.Value.Log().IsEnabled(LogLevel.Error)) { _instance.Value.Log().LogError("The Share API was called too early in the application lifecycle"); } return(false); } var dataPackageView = dataPackage.GetView(); var sharedData = new List <NSObject>(); var title = dataPackage.Properties.Title ?? string.Empty; if (dataPackageView.Contains(StandardDataFormats.Text)) { var text = await dataPackageView.GetTextAsync(); sharedData.Add(new DataActivityItemSource(new NSString(text), title)); } var uri = await GetSharedUriAsync(dataPackageView); if (uri != null && NSUrl.FromString(uri.OriginalString) is { } nsUrl) { sharedData.Add(new DataActivityItemSource(nsUrl, title)); } var activityViewController = new UIActivityViewController(sharedData.ToArray(), null); if (activityViewController.PopoverPresentationController != null && rootViewController.View != null) { activityViewController.PopoverPresentationController.SourceView = rootViewController.View; if (options.SelectionRect != null) { activityViewController.PopoverPresentationController.SourceRect = options.SelectionRect.Value.ToCGRect(); } else { activityViewController.PopoverPresentationController.SourceRect = new CGRect(rootViewController.View.Bounds.Width / 2, rootViewController.View.Bounds.Height / 2, 0, 0); activityViewController.PopoverPresentationController.PermittedArrowDirections = 0; } } if (options.Theme != ShareUITheme.Default) { activityViewController.OverrideUserInterfaceStyle = options.Theme == ShareUITheme.Light ? UIUserInterfaceStyle.Light : UIUserInterfaceStyle.Dark; } else { // Theme should match the application theme activityViewController.OverrideUserInterfaceStyle = CoreApplication.RequestedTheme == SystemTheme.Light ? UIUserInterfaceStyle.Light : UIUserInterfaceStyle.Dark; } var completionSource = new TaskCompletionSource <bool>(); activityViewController.CompletionWithItemsHandler = (NSString activityType, bool completed, NSExtensionItem[] returnedItems, NSError error) => { completionSource.SetResult(completed); }; await rootViewController.PresentViewControllerAsync(activityViewController, true); return(await completionSource.Task); }
internal static async Task <NSDraggingItem[]> CreateNativeDragDropData( DataPackageView data, Point startPoint) { NSDraggingItem draggingItem; var items = new List <NSDraggingItem>(); double maxFrameDimension = 300.0; // May be adjusted var defaultFrameRect = new CoreGraphics.CGRect(startPoint.X, startPoint.Y, 100, 30); /* Note that NSDraggingItems are required by the BeginDraggingSession methods. * Therefore, that is what is constructed here instead of pasteboard items. * * For several types such as NSString or NSImage, they implement the INSPasteboardWriting interface and * can therefore be used to directly construct an NSDraggingItem. * However, for other types (such as HTML) the full pasteboard item must be constructed first defining * both its type and string content. * * The dragging frame is used to represent the visual of the item being dragged. This could be a * preview of the image or sample text. At minimum, macOS requires the DraggingFrame property of the * NSDraggingItem to be set with a CGRect or the app will crash. It is however better to set both * the frame bounds and content at the same time with .SetDraggingFrame(). For caveats see: * https://developer.apple.com/documentation/appkit/nsdraggingitem/1528746-setdraggingframe * * Because Uno does not currently support the DragUI, this code only generates a real drag visual * for images where a visual is already defined. For other types such as text, no visual will be * generated. In the future, when DragUI and its corresponding image is supported, this can change. * */ if (data?.Contains(StandardDataFormats.Bitmap) ?? false) { NSImage?image = null; using (var stream = (await(await data.GetBitmapAsync()).OpenReadAsync()).AsStream()) { if (stream != null) { using (var ms = new MemoryStream()) { await stream.CopyToAsync(ms); ms.Flush(); ms.Position = 0; image = NSImage.FromStream(ms); } } } if (image != null) { draggingItem = new NSDraggingItem(image); // For an NSImage, we will use the image itself as the dragging visual. // The visual should be no larger than the max dimension setting and is therefore scaled. NSBitmapImageRep rep = new NSBitmapImageRep(image.CGImage); int width = (int)rep.PixelsWide; int height = (int)rep.PixelsHigh; double scale = maxFrameDimension / Math.Max(width, height); // Dragging frame must be set draggingItem.SetDraggingFrame( new CoreGraphics.CGRect(startPoint.X, startPoint.Y, width * scale, height * scale), image); items.Add(draggingItem); } } if (data?.Contains(StandardDataFormats.Html) ?? false) { var html = await data.GetHtmlFormatAsync(); if (!string.IsNullOrEmpty(html)) { var pasteboardItem = new NSPasteboardItem(); pasteboardItem.SetStringForType(html, NSPasteboard.NSPasteboardTypeHTML); draggingItem = new NSDraggingItem(pasteboardItem); draggingItem.DraggingFrame = defaultFrameRect; // Must be set items.Add(draggingItem); } } if (data?.Contains(StandardDataFormats.Rtf) ?? false) { var rtf = await data.GetRtfAsync(); if (!string.IsNullOrEmpty(rtf)) { // Use `NSPasteboardTypeRTF` instead of `NSPasteboardTypeRTFD` for max compatibility var pasteboardItem = new NSPasteboardItem(); pasteboardItem.SetStringForType(rtf, NSPasteboard.NSPasteboardTypeRTF); draggingItem = new NSDraggingItem(pasteboardItem); draggingItem.DraggingFrame = defaultFrameRect; // Must be set items.Add(draggingItem); } } if (data?.Contains(StandardDataFormats.StorageItems) ?? false) { var storageItems = await data.GetStorageItemsAsync(); if (storageItems.Count > 0) { // Not currently supported } } if (data?.Contains(StandardDataFormats.Text) ?? false) { var text = await data.GetTextAsync(); if (!string.IsNullOrEmpty(text)) { draggingItem = new NSDraggingItem((NSString)text); draggingItem.DraggingFrame = defaultFrameRect; // Must be set items.Add(draggingItem); } } if (data != null) { var uri = DataPackage.CombineUri( data.Contains(StandardDataFormats.WebLink) ? (await data.GetWebLinkAsync()).ToString() : null, data.Contains(StandardDataFormats.ApplicationLink) ? (await data.GetApplicationLinkAsync()).ToString() : null, data.Contains(StandardDataFormats.Uri) ? (await data.GetUriAsync()).ToString() : null); if (string.IsNullOrEmpty(uri) == false) { draggingItem = new NSDraggingItem(new NSUrl(uri)); draggingItem.DraggingFrame = defaultFrameRect; // Must be set items.Add(draggingItem); } } return(items.ToArray()); }
public static void SetContent(DataPackage /* ? */ content) { Uno.UI.Dispatching.CoreDispatcher.Main.RunAsync( Uno.UI.Dispatching.CoreDispatcherPriority.High, () => SetContentAsync(content)); }
private static DataPackageView GetFromNative(NSPasteboard pasteboard) { if (pasteboard is null) { throw new ArgumentException(nameof(pasteboard)); } var dataPackage = new DataPackage(); // Extract all the standard data format information from the pasteboard items. // Each format can only be used once; therefore, generally the last occurrence of the format will be the one used. foreach (NSPasteboardItem item in pasteboard.PasteboardItems) { if (item.Types.Contains(NSPasteboard.NSPasteboardTypeTIFF) || item.Types.Contains(NSPasteboard.NSPasteboardTypePNG)) { // Images may be very large, we never want to load them until they are needed. // Therefore, create a data provider used to asynchronously fetch the image. dataPackage.SetDataProvider( StandardDataFormats.Bitmap, async cancellationToken => { NSImage?image = null; /* Some apps, including Photos, don't appear to put image data in the pasteboard. * Instead, the image URL is provided although the type indicates it is an image. * * To get around this an image is read as follows: * (1) If the pasteboard contains an image type then: * (2) Attempt to read the image as an object (NSImage). * This may fail as some tested apps provide a URL although declare an image (Photos). * With other apps (such as web browsers) an image will be read correctly here. * (3) If reading as an NSImage object fails, attempt to read the image from a file URL (local images) * (4) If reading from a file URL fails, attempt to read the image from a URL (remote images) * * Reading as an NSImage object follows the docs here: * https://docs.microsoft.com/en-us/xamarin/mac/app-fundamentals/copy-paste#add-an-nsdocument */ var classArray = new Class[] { new Class("NSImage") }; if (pasteboard.CanReadObjectForClasses(classArray, null)) { NSObject[] objects = pasteboard.ReadObjectsForClasses(classArray, null); if (objects.Length > 0) { // Only use the first image found image = objects[0] as NSImage; } } // In order to get here the pasteboard must have declared it had image types. // However, if image is null, no objects were found and the image is likely a URL instead. if (image == null && item.Types.Contains(NSPasteboard.NSPasteboardTypeFileUrl)) { var url = item.GetStringForType(NSPasteboard.NSPasteboardTypeFileUrl); image = new NSImage(new NSUrl(url)); } if (image == null && item.Types.Contains(NSPasteboard.NSPasteboardTypeUrl)) { var url = item.GetStringForType(NSPasteboard.NSPasteboardTypeUrl); image = new NSImage(new NSUrl(url)); } if (image != null) { // Thanks to: https://stackoverflow.com/questions/13305028/monomac-best-way-to-convert-bitmap-to-nsimage/13355747 using (var imageData = image.AsTiff()) { var imgRep = NSBitmapImageRep.ImageRepFromData(imageData !) as NSBitmapImageRep; var data = imgRep !.RepresentationUsingTypeProperties(NSBitmapImageFileType.Png, null); return(new RandomAccessStreamReference(async ct => { return data.AsStream().AsRandomAccessStream().TrySetContentType("image/png"); })); } } else { // Return an empty image return(new RandomAccessStreamReference(async ct => { var stream = new MemoryStream(); stream.Position = 0; return stream.AsRandomAccessStream().TrySetContentType("image/png"); })); } }); } if (item.Types.Contains(NSPasteboard.NSPasteboardTypeHTML)) { var html = item.GetStringForType(NSPasteboard.NSPasteboardTypeHTML); if (html != null) { dataPackage.SetHtmlFormat(html); } } if (item.Types.Contains(NSPasteboard.NSPasteboardTypeRTF)) { var rtf = item.GetStringForType(NSPasteboard.NSPasteboardTypeRTF); if (rtf != null) { dataPackage.SetRtf(rtf); } } if (item.Types.Contains(NSPasteboard.NSPasteboardTypeFileUrl)) { // Drag and drop will use temporary URLs similar to: file:///.file/id=1234567.1234567 var tempFileUrl = item.GetStringForType(NSPasteboard.NSPasteboardTypeFileUrl); // Files may be very large, we never want to load them until they are needed. // Therefore, create a data provider used to asynchronously fetch the file. dataPackage.SetDataProvider( StandardDataFormats.StorageItems, async cancellationToken => { // Convert from a temp Url (see above example) into an absolute file path var fileUrl = new NSUrl(tempFileUrl); var file = await StorageFile.GetFileFromPathAsync(fileUrl.FilePathUrl.AbsoluteString); var storageItems = new List <IStorageItem>(); storageItems.Add(file); return(storageItems.AsReadOnly()); }); } if (item.Types.Contains(NSPasteboard.NSPasteboardTypeString)) { var text = item.GetStringForType(NSPasteboard.NSPasteboardTypeString); if (text != null) { dataPackage.SetText(text); } } if (item.Types.Contains(NSPasteboard.NSPasteboardTypeUrl)) { var url = item.GetStringForType(NSPasteboard.NSPasteboardTypeUrl); if (url != null) { DataPackage.SeparateUri( url, out string?webLink, out string?applicationLink); if (webLink != null) { dataPackage.SetWebLink(new Uri(webLink)); } if (applicationLink != null) { dataPackage.SetApplicationLink(new Uri(applicationLink)); } // Deprecated but still added for compatibility dataPackage.SetUri(new Uri(url)); } } } return(dataPackage.GetView()); }
public static void SetContent(DataPackage content) { //Setting to null doesn't reset the clipboard like for Android UIPasteboard.General.String = content?.Text ?? string.Empty; }
private static async Task SetToNativeAsync(DataPackage content, NSPasteboard pasteboard) { if (pasteboard is null) { throw new ArgumentException(nameof(pasteboard)); } var data = content?.GetView(); var declaredTypes = new List <string>(); string?uri = null; /* Note that order is somewhat important here. * * According to the docs: * "types should be ordered according to the preference of the source application, * with the most preferred type coming first" * https://developer.apple.com/documentation/appkit/nspasteboard/1533561-declaretypes?language=objc * * This means we want to process certain types like HTML/RTF before general plain text * as they are more specific. * * Types are also declared before setting */ // Declare types if (data?.Contains(StandardDataFormats.Html) ?? false) { declaredTypes.Add(NSPasteboard.NSPasteboardTypeHTML); } if (data?.Contains(StandardDataFormats.Rtf) ?? false) { // Use `NSPasteboardTypeRTF` instead of `NSPasteboardTypeRTFD` for max compatibility declaredTypes.Add(NSPasteboard.NSPasteboardTypeRTF); } if (data?.Contains(StandardDataFormats.Text) ?? false) { declaredTypes.Add(NSPasteboard.NSPasteboardTypeString); } if (data != null) { uri = DataPackage.CombineUri( data.Contains(StandardDataFormats.WebLink) ? (await data.GetWebLinkAsync()).ToString() : null, data.Contains(StandardDataFormats.ApplicationLink) ? (await data.GetApplicationLinkAsync()).ToString() : null, data.Contains(StandardDataFormats.Uri) ? (await data.GetUriAsync()).ToString() : null); if (string.IsNullOrEmpty(uri) == false) { declaredTypes.Add(NSPasteboard.NSPasteboardTypeUrl); } } pasteboard.DeclareTypes(declaredTypes.ToArray(), null); // Set content if (data?.Contains(StandardDataFormats.Html) ?? false) { var html = await data.GetHtmlFormatAsync(); pasteboard.SetStringForType(html ?? string.Empty, NSPasteboard.NSPasteboardTypeHTML); } if (data?.Contains(StandardDataFormats.Rtf) ?? false) { var rtf = await data.GetRtfAsync(); pasteboard.SetStringForType(rtf ?? string.Empty, NSPasteboard.NSPasteboardTypeRTF); } if (data?.Contains(StandardDataFormats.Text) ?? false) { var text = await data.GetTextAsync(); pasteboard.SetStringForType(text ?? string.Empty, NSPasteboard.NSPasteboardTypeString); } if (string.IsNullOrEmpty(uri) == false) { pasteboard.SetStringForType(uri !.ToString(), NSPasteboard.NSPasteboardTypeUrl); } return; }
public void InitContextMemu() { contextFlyout = new MenuFlyout(); MenuFlyoutItem copyItem = new MenuFlyoutItem { Text = "Copy", }; copyItem.Click += (s, e) => { var data = new Windows.ApplicationModel.DataTransfer.DataPackage(); data.Properties.Add("entity", (s as FrameworkElement).DataContext); Clipboard.SetContent(data); }; contextFlyout.Items.Add(copyItem); contextFlyout.Items.Add(new MenuFlyoutSeparator()); MenuFlyoutItem addItem = new MenuFlyoutItem { Text = "Add", }; addItem.Click += (s, e) => { var command = DataContext.GetType().GetMethod("Add"); if (command != null) { command.Invoke(DataContext, new object[0]); } }; contextFlyout.Items.Add(addItem); MenuFlyoutItem openItem = new MenuFlyoutItem { Text = "Open", }; openItem.Click += (s, e) => { var command = DataContext.GetType().GetMethod("Open"); if (command != null) { command.Invoke(DataContext, new object[1] { (s as FrameworkElement).DataContext }); } }; contextFlyout.Items.Add(openItem); MenuFlyoutItem removeItem = new MenuFlyoutItem { Text = "Remove", }; removeItem.Click += (s, e) => { var command = DataContext.GetType().GetMethod("Remove"); if (command != null) { command.Invoke(DataContext, new object[1] { (s as FrameworkElement).DataContext }); } }; contextFlyout.Items.Add(removeItem); //contextFlyout.ShowAt(targetControl, new Point(x,y)); }
public static void SetContent(DataPackage content) { DataPackage.SetToNativeClipboard(content); }
internal static Task SetToNativeClipboardAsync(DataPackage content) => SetToNativeAsync(content, NSPasteboard.GeneralPasteboard);
public static DataPackageView GetContent() { return(DataPackage.GetFromNativeClipboard()); }
internal static Task SetContentAsync(DataPackage content) => DataPackage.SetToNativeClipboardAsync(content);