private string CopySelectedText() { if (null == scriptState) return string.Empty; string textToCopy = scriptState.textBuffer.GetText(scriptState.selectionStart, scriptState.selectionEnd); textToCopy = textToCopy.Replace("\n", "\r\n"); try { RichTextFormatter formatter = new RichTextFormatter( scriptState.textBuffer, codeFragmentManager); string formattedContent = formatter.Format( scriptState.selectionStart, scriptState.selectionEnd); DataObject clipboardData = new DataObject(); clipboardData.SetData(DataFormats.Text, textToCopy); clipboardData.SetData(DataFormats.Rtf, formattedContent); Clipboard.SetDataObject(clipboardData); } catch (System.Runtime.InteropServices.COMException) { System.Threading.Thread.Sleep(0); try { Clipboard.SetData(DataFormats.Text, textToCopy); } catch (System.Runtime.InteropServices.COMException) { MessageBox.Show("Can't Access Clipboard"); } } return textToCopy; }
public static void ToClipboard(this List<FrameworkElement> elements) { var builderTabbedText = new StringBuilder(); var builderCsvText = new StringBuilder(); foreach (var element in elements) { string tabbedText = element.DataContext.ToString(); string csvText = element.DataContext.ToString(); builderTabbedText.AppendLine(tabbedText); builderCsvText.AppendLine(csvText); } // data object to hold our different formats representing the element var dataObject = new DataObject(); dataObject.SetText(builderTabbedText.ToString()); // Convert the CSV text to a UTF-8 byte stream before adding it to the container object. var bytes = Encoding.UTF8.GetBytes(builderCsvText.ToString()); var stream = new System.IO.MemoryStream(bytes); dataObject.SetData(DataFormats.CommaSeparatedValue, stream); // lets start with the text representation // to make is easy we will just assume the object set as the DataContext has the ToString method overrideen and we use that as the text dataObject.SetData(DataFormats.CommaSeparatedValue, stream); // now place our object in the clipboard Clipboard.SetDataObject(dataObject, true); }
public DataObject BuildDesktopInternetShortcutDragger(string filetitle, string url) { // The magic happens here thanks to: http://www.codeproject.com/KB/cs/draginternetshortcut.aspx byte[] title = Encoding.ASCII.GetBytes(filetitle + ".url"); var fileGroupDescriptor = new byte[336]; title.CopyTo(fileGroupDescriptor, 76); fileGroupDescriptor[0] = 0x1; fileGroupDescriptor[4] = 0x40; fileGroupDescriptor[5] = 0x80; fileGroupDescriptor[72] = 0x78; var fileGroupDescriptorStream = new MemoryStream(fileGroupDescriptor); byte[] urlByteArray = Encoding.ASCII.GetBytes(url); var urlStream = new MemoryStream(urlByteArray); string contents = "[InternetShortcut]" + Environment.NewLine + "URL=" + url + Environment.NewLine; byte[] contentsByteArray = Encoding.ASCII.GetBytes(contents); var contentsStream = new MemoryStream(contentsByteArray); var dataobj = new DataObject(); dataobj.SetData("FileGroupDescriptor", fileGroupDescriptorStream); dataobj.SetData("FileContents", contentsStream); dataobj.SetData("UniformResourceLocator", urlStream); return dataobj; }
void AssociatedObject_MouseLeave(object sender, MouseEventArgs e) { if (this._isMouseClicked) { // set the item's DataContext as the data to be transferred. var dragObject = this.AssociatedObject.DataContext as IDragable; if (dragObject != null) { this._wasDragging = true; var data = new DataObject(); var parent = ItemsControl.ItemsControlFromItemContainer(this.AssociatedObject) as ListBox; IList list = null; if (this.DragSourceBinding == null) { // Pass the raw ItemSource as the drag object. list = (IList)Activator.CreateInstance((typeof(List <>).MakeGenericType(dragObject.DataType))); if (!this.AssociatedObject.IsSelected) { list.Add(this.AssociatedObject.DataContext); } foreach (var item in parent.SelectedItems) { list.Add(item); } } else { // Pass the Binding object under the ItemSource as the drag object. var propertyName = ((Binding)this.DragSourceBinding as Binding).Path.Path; var pd = TypeDescriptor.GetProperties(this.AssociatedObject.DataContext).Find(propertyName, false); list = (IList)Activator.CreateInstance((typeof(List <>).MakeGenericType(pd.PropertyType))); if (!this.AssociatedObject.IsSelected) { list.Add(pd.GetValue(this.AssociatedObject.DataContext)); } foreach (var item in parent.SelectedItems) { list.Add(pd.GetValue(item)); } } data.SetData(list.GetType(), list); // Send the ListBox that initiated the drag, so we can determine if the drag and drop are different or not. data.SetData(typeof(string), parent.Uid); //data.SetData(dragObject.DataType, this.AssociatedObject.DataContext); System.Windows.DragDrop.DoDragDrop(parent, data, DragDropEffects.Copy); //System.Windows.DragDrop.DoDragDrop(this.AssociatedObject, data, DragDropEffects.Move); } } this._isMouseClicked = false; }
// ******************************************************************** // Public Methods // ******************************************************************** #region Public Methods /// <summary> /// Copies the plotToCopy as a bitmap to the clipboard, and copies the /// chartControl to the clipboard as tab separated values. /// </summary> /// <param name="plotToCopy"></param> /// <param name="chartControl"></param> /// <param name="width">Width of the bitmap to be created</param> /// <param name="height">Height of the bitmap to be created</param> public static void CopyChartToClipboard(FrameworkElement plotToCopy, XYLineChart chartControl, double width, double height) { Bitmap bitmap = CopyFrameworkElementToBitmap(plotToCopy, width, height); string text = ConvertChartToSpreadsheetText(chartControl, '\t'); MemoryStream csv = new MemoryStream(Encoding.UTF8.GetBytes(ConvertChartToSpreadsheetText(chartControl, ','))); DataObject dataObject = new DataObject(); dataObject.SetData(DataFormats.Bitmap, bitmap); dataObject.SetData(DataFormats.Text, text); dataObject.SetData(DataFormats.CommaSeparatedValue, csv); Clipboard.SetDataObject(dataObject); }
protected override void OnMouseMove(MouseEventArgs e) { base.OnMouseMove(e); if (e.LeftButton == MouseButtonState.Pressed) { DataObject data = new DataObject(); data.SetData("Item", MainWindow.player.Inventory[Index]); data.SetData("Object", this); DragDrop.DoDragDrop(this, data, DragDropEffects.Move); } }
// ******************************************************************** // Public Methods // ******************************************************************** #region Public Methods public static void CopyChartToClipboard(FrameworkElement plotToCopy, ChartControl chartControl, double width, double height) { plotToCopy = plotToCopy ?? chartControl; System.Drawing.Bitmap bitmap = CopyFrameworkElementToBitmap(plotToCopy, width, height); DataObject dataObject = new DataObject(); dataObject.SetData(DataFormats.Bitmap, bitmap); if(chartControl != null) { string text = ChartUtilities.ConvertChartToSpreadsheetText(chartControl, '\t'); MemoryStream csv = new MemoryStream(Encoding.UTF8.GetBytes(ChartUtilities.ConvertChartToSpreadsheetText(chartControl, ','))); dataObject.SetData(DataFormats.Text, text); dataObject.SetData(DataFormats.CommaSeparatedValue, csv); } Clipboard.SetDataObject(dataObject); }
protected override void OnMouseMove(MouseEventArgs e) { base.OnMouseMove(e); if (e.LeftButton == MouseButtonState.Pressed) { DataObject data = new DataObject(); data.SetData(DataFormats.StringFormat, circleUI.Fill.ToString()); data.SetData("Double", circleUI.Height); data.SetData("Object", this); DragDrop.DoDragDrop(this, data, DragDropEffects.Copy | DragDropEffects.Move); } }
protected override IDataObject GetDataObject(SharpTreeNode[] nodes) { var data = new DataObject(); var paths = nodes.OfType<FileSystemNode>().Select(n => n.FullPath).ToArray(); data.SetData(DataFormats.FileDrop, paths); return data; }
/// <summary> /// /// </summary> /// <param name="container"></param> /// <param name="ic"></param> public void SetClipboard(IPageContainer container, IImageCache ic) { try { if (container == null || container.Template == null) { return; } using (var bitmap = new Bitmap((int)container.Template.Width, (int)container.Template.Height)) { using (var ms = MakeMetafileStream(bitmap, container, ic)) { var data = new WPF.DataObject(); data.SetData(WPF.DataFormats.EnhancedMetafile, ms); WPF.Clipboard.SetDataObject(data, true); } } } catch (Exception ex) { Debug.WriteLine(ex.Message); Debug.WriteLine(ex.StackTrace); } }
//http://stackoverflow.com/questions/1719013/obtaining-dodragdrop-dragsource //In the call to DoDragDrop, add your object as an extra format: // var dragSource = this; // var data = "Hello"; // var dataObj = new DataObject(data); // dataObj.SetData("DragSource", dragSource); // DragDrop.DoDragDrop(dragSource, dataObj, DragDropEffects.Copy); //Now in the OnDrag handler it is easy to get the drag source: //protected override void OnDrop(DragEventArgs e) //{ // var data = e.Data.GetData(DataFormats.Text); // var dragSource = e.Data.GetData("DragSource"); // ... //} //In some cases, knowing the source object itself is sufficient to get the data you require to complete the drag operation, in which case the above boils down to: // DragDrop.DoDragDrop(dragSource, dragSource, DragDropEffects.Copy); // ... // var dragSource = e.Data.GetData(typeof(MyDragSource)) private void Border_MouseLeftButtonDown(object sender, MouseButtonEventArgs e) { Label l_Label = sender as Label; var l_DataObject = new DataObject(l_Label.Content); l_DataObject.SetData("String", l_Label.Content); DragDrop.DoDragDrop((System.Windows.DependencyObject)sender, l_DataObject, DragDropEffects.Copy); }
public override IDataObject Copy(SharpTreeNode[] nodes) { var data = new DataObject(); var paths = SharpTreeNode.ActiveNodes.Cast<FileSystemNode>().Select(n => n.FullPath).ToArray(); data.SetData(typeof(string[]), paths); return data; }
/// <summary> /// /// </summary> /// <param name="shapes"></param> /// <param name="width"></param> /// <param name="height"></param> /// <param name="properties"></param> /// <param name="ic"></param> public void SetClipboard( IEnumerable <BaseShape> shapes, double width, double height, ImmutableArray <ShapeProperty> properties, IImageCache ic) { try { using (var bitmap = new Bitmap((int)width, (int)height)) { using (var ms = MakeMetafileStream(bitmap, shapes, properties, ic)) { var data = new WPF.DataObject(); data.SetData(WPF.DataFormats.EnhancedMetafile, ms); WPF.Clipboard.SetDataObject(data, true); } } } catch (Exception ex) { Debug.Print(ex.Message); Debug.Print(ex.StackTrace); } }
private DataObject GetDragDataObject(DependencyObject dragSource) { String format = (String)Application.Current.Resources["DragAndDropRowHeaderFormat"]; DataObject data = new DataObject(); data.SetData(format, dragSource); return data; }
public virtual DataObject GetDataObject(UIElement draggedElt) { string serializedElt = XamlWriter.Save(draggedElt); DataObject obj = new DataObject(); obj.SetData(supportedFormat,serializedElt); return obj; }
private void List_MouseMove(object sender, MouseEventArgs e) { if (e.LeftButton == MouseButtonState.Pressed && LvSongList.SelectedItems != null) { DataObject obj = new DataObject(); obj.SetData(typeof (ObservableCollection<Song>), LvSongList.SelectedItems); DragDrop.DoDragDrop(LvSongList, obj, DragDropEffects.Copy | DragDropEffects.Move); } }
private void materialPreview_MouseMove(object sender, MouseEventArgs e) { if (e.LeftButton == MouseButtonState.Pressed) { System.Windows.DataObject dataObject = new System.Windows.DataObject(); dataObject.SetData("Object", material); DragDrop.DoDragDrop(this, dataObject, System.Windows.DragDropEffects.Copy); } }
private void lightPreview_MouseMove(object sender, MouseEventArgs e) { if (e.LeftButton == MouseButtonState.Pressed) { System.Windows.DataObject dataObject = new System.Windows.DataObject(); dataObject.SetData("Object", light); DragDrop.DoDragDrop(this, dataObject, System.Windows.DragDropEffects.Copy); //Console.WriteLine(_elementsCol.ElementAt(gotowe_ListView.SelectedIndex).ToString()); } }
private void HandleDragDelta(object sender, DragContainerEventArgs e) { // Don't actually start the drag unless the mouse has moved for enough away // from the initial MouseDown point. Point currentPoint = e.CurrentPosition; if (Math.Abs(currentPoint.X - dragStartPoint.X) > SystemParameters.MinimumHorizontalDragDistance || Math.Abs(currentPoint.Y - dragStartPoint.Y) > SystemParameters.MinimumVerticalDragDistance) { this.isMouseDown = false; // Since we have to have the data before the drag starts, we don't allow a drag for data that // is not cached to avoid blocking the UI while the data is fetched before the drag starts. if (IsDataAvailable()) { IsInDrag = true; int width = (int)this.RenderSize.Width; int height = (int)this.RenderSize.Height; RenderTargetBitmap rtb = new RenderTargetBitmap(width, height, 96.0, 96.0, PixelFormats.Pbgra32); // TODO: use actual dpi. rtb.Render(this); ConstrainSize(ref width, ref height, 200); BitmapSource ghostImage = ResizeImage(rtb, width, height); this.CaptureMouse(); Point mousePoint = new Point(0.5 * width, 0.5 * height); #if USE_STANDARD_DRAGDROP var dataObject = new System.Windows.DataObject(); var items = GetData(); foreach (var item in items) { dataObject.SetData(item.Key, item.Value); } DragDrop.DoDragDrop(this, dataObject, DragDropEffects.Copy); #else try { DragSourceHelper.DoDragDrop(this, ghostImage, mousePoint, DragDropEffects.Copy, GetData()); } catch (COMException) { // DragDropLib is buggy. Fail silently if this happens. } #endif this.ReleaseMouseCapture(); IsInDrag = false; } } }
private void MenuItem_CopyFile_Click(object sender, System.Windows.RoutedEventArgs e) { if (!String.IsNullOrEmpty(_filename)) { string[] file = new string[1]; file[0] = _filename; System.Windows.DataObject dataObject = new System.Windows.DataObject(); dataObject.SetData(System.Windows.DataFormats.FileDrop, file); System.Windows.Clipboard.SetDataObject(dataObject, true); } }
public DataObject GetDataObject(UIElement draggedElement, Point location) { DataObject data = new DataObject(); ToolboxItem item = GetToolboxItem(draggedElement); if (item != null) { item.IsBeingDragged = true; data.SetData("Helios.Visual", item.CreateControl()); } return data; }
protected override IDataObject GetDataObject(SharpTreeNode[] nodes) { string[] data = nodes .OfType<XamlOutlineNode>() .Select(item => item.GetMarkupText()) .ToArray(); var dataObject = new DataObject(); dataObject.SetData(typeof(string[]), data); return dataObject; }
/// <summary> /// Method to invoke when the Copy command is executed. /// </summary> private void Copy() { List <ElementModel> clipData = new List <ElementModel>(); clipData.AddRange(SelectedItems.Select(x => x.ElementModel).ToList()); IDataObject dataObject = new DataObject(ClipboardFormatName); dataObject.SetData(clipData); Clipboard.SetDataObject(dataObject, true); }
/// <summary> /// Places the provided data on the clipboard overriding what is currently in the clipboard. /// </summary> /// <param name="isSingleLine">Indicates whether a single line was automatically cut/copied by /// the editor. If <c>true</c> the clipboard contents are tagged with a special moniker.</param> public static void SetClipboardData(string html, string rtf, string unicode, bool isSingleLine, bool isBoxCopy) { DataObject data = new DataObject(); if (unicode != null) { data.SetText(unicode, TextDataFormat.UnicodeText); data.SetText(unicode, TextDataFormat.Text); } if (html != null) { data.SetText(GetHtmlForClipboard(html), TextDataFormat.Html); } if (rtf != null) { data.SetText(rtf, TextDataFormat.Rtf); } if (isSingleLine) { data.SetData(ClipboardLineBasedCutCopyTag, new object()); } if (isBoxCopy) { data.SetData(BoxSelectionCutCopyTag, new object()); } try { // Use delay rendering to set the data in the clipboard to prevent 2 clipboard change // notifications to clipboard change listeners. Clipboard.SetDataObject(data, false); } catch (System.Runtime.InteropServices.ExternalException) { } }
private void TableName_MouseMove(object sender, MouseEventArgs e) { if (e.LeftButton == MouseButtonState.Pressed) { DataObject obj = new DataObject(); object[] dataValues = new object[] { this.GetType(), this }; obj.SetData(DataFormats.Serializable, dataValues); DragDrop.DoDragDrop(this, obj, DragDropEffects.Copy | DragDropEffects.Move); } }
private static void DragAndDrop(object sender, MouseEventArgs e) { Control control = (Control)sender; if (e.LeftButton == MouseButtonState.Pressed) { DataObject data = new DataObject(); data.SetData("Label", control); System.Windows.DragDrop.DoDragDrop(control, data, DragDropEffects.Copy | DragDropEffects.Move); RoutedEventArgs neweventargs = new RoutedEventArgs(RaahausEvent); (control).RaiseEvent(neweventargs); } }
private void CopyToClipboard(bool cut) { string[] files = GetSelection(); if (files != null) { System.Windows.IDataObject data = new System.Windows.DataObject(System.Windows.DataFormats.FileDrop, files); MemoryStream memo = new MemoryStream(4); byte[] bytes = new byte[] { (byte)(cut ? 2 : 5), 0, 0, 0 }; memo.Write(bytes, 0, bytes.Length); data.SetData("Preferred DropEffect", memo); System.Windows.Clipboard.SetDataObject(data, true); } }
/// <summary> /// Sets managed data to a clipboard DataObject. /// </summary> /// <param name="dataObject">The DataObject to set the data on.</param> /// <param name="format">The clipboard format.</param> /// <param name="data">The data object.</param> /// <remarks> /// Because the underlying data store is not storing managed objects, but /// unmanaged ones, this function provides intelligent conversion, allowing /// you to set unmanaged data into the COM implemented IDataObject.</remarks> public static void SetDataEx(this IDataObject dataObject, string format, object data) { DataFormat dataFormat = DataFormats.GetDataFormat(format); // Initialize the format structure var formatETC = new FORMATETC(); formatETC.cfFormat = (short)dataFormat.Id; formatETC.dwAspect = DVASPECT.DVASPECT_CONTENT; formatETC.lindex = -1; formatETC.ptd = IntPtr.Zero; // Try to discover the TYMED from the format and data TYMED tymed = GetCompatibleTymed(format, data); // If a TYMED was found, we can use the system DataObject // to convert our value for us. if (tymed != TYMED.TYMED_NULL) { formatETC.tymed = tymed; // Set data on an empty DataObject instance var conv = new System.Windows.DataObject(); conv.SetData(format, data, true); // Now retrieve the data, using the COM interface. // This will perform a managed to unmanaged conversion for us. STGMEDIUM medium; ((ComIDataObject)conv).GetData(ref formatETC, out medium); try { // Now set the data on our data object ((ComIDataObject)dataObject).SetData(ref formatETC, ref medium, true); } catch { // On exceptions, release the medium ReleaseStgMedium(ref medium); throw; } } else { // Since we couldn't determine a TYMED, this data // is likely custom managed data, and won't be used // by unmanaged code, so we'll use our custom marshaling // implemented by our COM IDataObject extensions. ComDataObjectExtensions.SetManagedData((ComIDataObject)dataObject, format, data); } }
public static void SetFileDropList(DropEffect effect, string[] files) { files.ThrowIfNull("files"); IDataObject iDataObj = new DataObject(DataFormats.FileDrop, files); MemoryStream dropEffect = new MemoryStream(); byte[] bytes = new byte[] { (byte)effect, 0, 0, 0 }; dropEffect.Write(bytes, 0, bytes.Length); dropEffect.SetLength(bytes.Length); iDataObj.SetData("Preferred DropEffect", dropEffect); Clipboard.SetDataObject(iDataObj); }
private void OnMouseDrag(object sender, MouseEventArgs e) { if (e.LeftButton == MouseButtonState.Pressed && !IS_DRAGGING) { IS_DRAGGING = true; Console.WriteLine("dragging"); DataObject dataObject = GetDataObject(); dataObject.SetData("ClipboardObject", this); DragDrop.DoDragDrop((Border)sender, dataObject, DragDropEffects.Copy | DragDropEffects.Move); Console.WriteLine("finished"); IS_DRAGGING = false; } // TODO: visual drag effect }
public void Defaults () { DataObject dobj = new DataObject (); Assert.Throws<SecurityException> (() => dobj.GetFormats (), "GetFormats ()"); Assert.Throws<SecurityException> (() => dobj.GetFormats (true), "GetFormats (true)"); Assert.Throws<SecurityException> (() => dobj.GetFormats (false), "GetFormats (false)"); Assert.Throws<SecurityException> (() => dobj.GetData (DataFormats.FileDrop), "GetData (string)"); Assert.Throws<SecurityException> (() => dobj.GetData (DataFormats.FileDrop, true), "GetData (string,true)"); Assert.Throws<SecurityException> (() => dobj.GetData (DataFormats.FileDrop, false), "GetData (string,false)"); Assert.Throws<SecurityException> (() => dobj.GetData (typeof(string)), "GetData (Type)"); Assert.Throws<SecurityException> (() => dobj.GetDataPresent (DataFormats.FileDrop), "GetDataPresent (string)"); Assert.Throws<SecurityException> (() => dobj.GetDataPresent (DataFormats.FileDrop, true), "GetDataPresent (string,true)"); Assert.Throws<SecurityException> (() => dobj.GetDataPresent (DataFormats.FileDrop, false), "GetDataPresent (string,false)"); Assert.Throws<SecurityException> (() => dobj.GetDataPresent (typeof (string)), "GetDataPresent (Type)"); Assert.Throws<SecurityException> (() => dobj.SetData (DataFormats.FileDrop), "SetData (string)"); Assert.Throws<SecurityException> (() => dobj.SetData (DataFormats.FileDrop, true), "SetData (string,true)"); Assert.Throws<SecurityException> (() => dobj.SetData (DataFormats.FileDrop, false), "SetData (string,false)"); Assert.Throws<SecurityException> (() => dobj.SetData (typeof (string)), "SetData (Type)"); }
private void OnMouseDrag(object sender, MouseEventArgs e) { if (e.LeftButton == MouseButtonState.Pressed && !IS_DRAGGING) { IS_DRAGGING = true; Icon.Visibility = Visibility.Hidden; Console.WriteLine("dragging c"); DataObject dataObject = new DataObject(); dataObject.SetData("Category", this); DragDrop.DoDragDrop((Border)sender, dataObject, DragDropEffects.Copy | DragDropEffects.Move); Console.WriteLine("finished c"); IS_DRAGGING = false; Icon.Visibility = Visibility.Visible; } // TODO: visual drag effect }
public static DataObject ToDataObject(this TransferDataSource data) { var retval = new DataObject (); foreach (var type in data.DataTypes) { var value = data.GetValue (type); if (type == TransferDataType.Text) retval.SetText ((string)value); else if (type == TransferDataType.Uri) { var uris = new StringCollection (); uris.Add (((Uri)value).LocalPath); retval.SetFileDropList (uris); } else retval.SetData (type.Id, TransferDataSource.SerializeValue (value)); } return retval; }
private void RichTextBox_Pasting(object sender, DataObjectPastingEventArgs e) { //不是字符串的粘贴都取消 if (e.SourceDataObject.GetDataPresent(DataFormats.UnicodeText)) { //重新获取字符串并设置DataObject var text = e.SourceDataObject.GetData(DataFormats.UnicodeText); var dataObj = new DataObject(); dataObj.SetData(DataFormats.UnicodeText, text); e.DataObject = dataObj; } else e.CancelCommand(); //if (e.FormatToApply != "Bitmap") //{ //e.CancelCommand(); //} }
/// <summary> /// /// </summary> /// <param name="container"></param> /// <param name="ic"></param> public void SetClipboard(Container container, IImageCache ic) { try { using (var bitmap = new Bitmap((int)container.Width, (int)container.Height)) { using (var ms = MakeMetafileStream(bitmap, container, ic)) { var data = new WPF.DataObject(); data.SetData(WPF.DataFormats.EnhancedMetafile, ms); WPF.Clipboard.SetDataObject(data, true); } } } catch (Exception ex) { Debug.Print(ex.Message); Debug.Print(ex.StackTrace); } }
public DataObject GetDataObject() { DataObject dataObject = new DataObject(); foreach (string format in dataMap.Keys) { try { object data = dataMap[format]; if (data != null) { dataObject.SetData(format, data); } } catch (ExternalException ex) { Console.WriteLine($"Error {ex.ErrorCode}: {ex.Message}"); } } return(dataObject); }
private void UIElement_OnMouseMove(object sender, MouseEventArgs e) { TreeView item = e.Source as TreeView; if (item != null && e.LeftButton == MouseButtonState.Pressed) { if (item.SelectedItem != null) { DataObject dataObject = new DataObject(); if (!(item.SelectedItem is CameraGroupViewModel) && (item.SelectedItem is CameraItemViewModel)) { //Create a stream data that contain some infomations //Format data: camurl;ip;type String data = (item.SelectedItem as CameraItemViewModel).CamUrl + ";" + (item.SelectedItem as CameraItemViewModel).Ip + ";" + (item.SelectedItem as CameraItemViewModel).Type; //End create dataObject.SetData("MyTreeViewItem", data); DragDrop.DoDragDrop(item, dataObject, DragDropEffects.Copy); } } } }
public override void Execute(object parameter) { var active = MainViewModel.ActiveDirectoryContainer.ActiveView; if (!active.FileSystem.IsWindowsFileSystem) { MessageBox.Show("To polecenie działa tylko w windows'owym systemie plików"); return; } //get items to copy var items = MainViewModel.GetSelectedItems(); if (items.Length == 0) { MessageBox.Show("Zaznacz obiekty do skopiowania"); return; } //get paths to copy from items var paths = new StringCollection(); foreach (IDirectoryViewItem item in items) paths.Add(item.FullName); //and here goes magic //set special binary data that indicates that file must be copy byte[] moveEffect = new byte[] { 5, 0, 0, 0 };//copy var dropEffect = new MemoryStream(); dropEffect.Write(moveEffect, 0, moveEffect.Length); //set data object with file's paths DataObject data = new DataObject(); data.SetFileDropList(paths); data.SetData("Preferred DropEffect", dropEffect); //set data object in clipboard Clipboard.Clear(); //dropEffect.Close(); Clipboard.SetDataObject(data, true); }
/// <summary> /// Gets a DataObject that contains all restorable formats of the clipboard. /// </summary> /// <returns></returns> public static IDataObject GetDataObject() { IDataObject orig = Clipboard.GetDataObject(); DataObject obj = new DataObject(); foreach (string format in orig.GetFormats()) { // Only copy supported formats that can be saved and restored if (format == "Bitmap" || format == "FileDrop" || format == "FileName" || format == "FileNameW" || format == "HTML Format" || format == "Rich Text Format" || format == "Text" || format == "UnicodeText") { obj.SetData(format, orig.GetData(format)); } } return obj; }
public static IDataObject GetDataObject() { var dataObject = new DataObject(); // Beside copying and pasting UnicodeText to/from pasteboard // editor inserts booleans like "VisualStudioEditorOperationsLineCutCopyClipboardTag" // which allows editor to know whole line was copied into pasteboard so on paste // it inserts line into new line, so we enumerate over all types and if length == 1 // we just assume it's boolean we set in method above foreach (var type in pasteboard.Types) { if (type == DataFormats.UnicodeText) { dataObject.SetText(pasteboard.GetStringForType(type)); continue; } var data = pasteboard.GetDataForType(type); if (data != null && data.Length == 1) { dataObject.SetData(type, data: data [0] != 0); } } return(dataObject); }
/// <summary> /// Method to invoke when the Cut command is executed. /// </summary> private void Cut() { List <ElementModel> clipData = new List <ElementModel>(); clipData.AddRange(SelectedItems.Select(x => x.ElementModel).ToList()); IDataObject dataObject = new DataObject(ClipboardFormatName); dataObject.SetData(clipData); Clipboard.SetDataObject(dataObject, true); var itemsToCut = SelectedItems.ToList(); DeselectAll(); foreach (var elementModelViewModel in itemsToCut) { var parentToLeave = elementModelViewModel.ParentViewModel as ElementModelViewModel; if (parentToLeave != null) { PropModelServices.Instance().RemoveFromParent(elementModelViewModel.ElementModel, parentToLeave.ElementModel); } } OnModelsChanged(); }
public void GetClipboardData() { var data = Clipboard.GetDataObject(); var msg = "Hello World!"; var now = (DateTime.Now.ToUniversalTime() - epoch).TotalSeconds.ToString(); var sanitisedTimestamp = now.Split('.')[0]; var skypeMessageFragment = this.GenerateFragment(quoteText: msg, timestamp: sanitisedTimestamp); var dataobj = new DataObject(); dataobj.SetData(FormatText, msg); dataobj.SetData(FormatUnicodeText, msg); dataobj.SetData(FormatSystemString, msg); dataobj.SetData(FormatSkypeMessageFragment, new MemoryStream(Encoding.UTF8.GetBytes(skypeMessageFragment))); dataobj.SetData(FormatLocale, new MemoryStream(BitConverter.GetBytes(CultureInfo.CurrentCulture.LCID))); dataobj.SetData(FormatOEMText, msg); Clipboard.Clear(); Clipboard.SetDataObject(dataobj); }
/// <summary> /// Copies the selected cells. /// </summary> /// <param name="separator">The separator.</param> public void Copy(string separator) { var text = this.SelectionToString(separator); var array = this.SelectionToArray(); var dataObject = new DataObject(); dataObject.SetText(text); if (AreAllElementsSerializable(array)) { try { dataObject.SetData(typeof(DataGrid), array); } catch (Exception e) { // nonserializable values? Debug.WriteLine(e); } } Clipboard.SetDataObject(dataObject); }
/// <summary> /// Controls pasted values on an input that is meant to only accept a dollar amount as input. /// That is, digits and a single decimal, followed by a maximum of two digits. /// </summary> /// <param name="sender"> /// The input raising the event. /// </param> /// <param name="e"> /// The paste data arguments. /// </param> private void OnDollarValueTextPasting(object sender, DataObjectPastingEventArgs e) { // Automatically try to parse the pasted data as a decimal and convert it to the // appropriate string format. On failure, deny the paste. string pastedText = (string)e.DataObject.GetData(typeof(string)); DataObject newObj = new DataObject(); if (pastedText != null) { pastedText = m_regexDollarValueOnlyValidation.Replace(pastedText, ""); decimal asDecimal; if(decimal.TryParse(pastedText, out asDecimal)) { pastedText = Math.Round(asDecimal, 2).ToString(); } else { // On conversion failure, just refuse paste. pastedText = string.Empty; } newObj.SetData(DataFormats.Text, pastedText); } e.DataObject = newObj; }
/// <summary> /// For enforcing digit-only input into the blocked payload byte estimation TextBox when the /// user pastes clipboard content into the box. /// </summary> /// <param name="sender"> /// Who dun' it. /// </param> /// <param name="e"> /// Event parameters. /// </param> private void OnDigitOnlyTextPasting(object sender, DataObjectPastingEventArgs e) { // Simply use our existing regex to blow away all non-digit text, then replace the // payload of the paste with the result. string pastedText = (string)e.DataObject.GetData(typeof(string)); DataObject newObj = new DataObject(); if(pastedText != null) { newObj.SetData(DataFormats.Text, m_regexDigitOnlyValidation.Replace(pastedText, "")); } e.DataObject = newObj; }
int _DragEvent(int event_, byte[] b) { if (!_isDragMode) { return(0); } DDEvent ev = (DDEvent)event_; if (ev == DDEvent.Leave) { if (!_wTargetControl.Is0) { _InvokeDT(_wTargetControl, ev, 0, 0, default); _wTargetControl = default; } return(0); } var a = Serializer_.Deserialize(b); int effect = a[0], keyState = a[1]; POINT pt = new(a[2], a[3]); if (ev == DDEvent.Enter) { _data = new System.Windows.DataObject(); var t = new DDData { files = a[4], shell = a[5], text = a[6], linkName = a[7] }; if (t.files != null) { _data.SetData("FileDrop", t.files); } if (t.shell != null) { _SetDataBytes("Shell IDList Array", t.shell); } if (t.text != null) { _data.SetData("UnicodeText", t.text); } if (t.linkName != null) { _SetDataBytes("FileGroupDescriptorW", t.linkName); } //workaround for: SetData writes byte[] in wrong format, probably serialized void _SetDataBytes(string name, byte[] a) => _data.SetData(name, new MemoryStream(a), false); } int ef = 0; var w = _wWindow.ChildFromXY(pt, WXYCFlags.ScreenXY); if (w.Is0) { w = _wWindow; } if (w != _wTargetControl && !_wTargetControl.Is0) { _InvokeDT(_wTargetControl, DDEvent.Leave, 0, 0, default); _wTargetControl = default; } if (!w.Is0 && w.IsOfThisProcess && w.IsEnabled(true)) { if (ev != 0 && _wTargetControl.Is0) { if (ev == DDEvent.Over) { ev = 0; } else { _InvokeDT(w, DDEvent.Enter, effect, keyState, pt); } } ef = _InvokeDT(_wTargetControl = w, ev, effect, keyState, pt); } if (ev == DDEvent.Drop) { _wTargetControl = default; } int _InvokeDT(wnd w, DDEvent ev, int effect, int keyState, POINT pt) { if (w.IsOfThisThread) { return(_InvokeDropTarget(w, ev, effect, keyState, pt)); } var d = HwndSource.FromHwnd(w.Window.Handle)?.Dispatcher; return(d?.Invoke(() => _InvokeDropTarget(w, ev, effect, keyState, pt)) ?? 0); } return(ef); }
public virtual void CsvPaste() { using (var interactive = Prepare()) { interactive.Invoke(() => { var dataObject = new DataObject(); dataObject.SetText("fob"); var stream = new MemoryStream(UTF8Encoding.Default.GetBytes("\"abc,\",\"fob\",\"\"\"fob,\"\"\",oar,baz\"x\"oar,\"baz,\"\"x,\"\"oar\",, ,oar,\",\"\",\"\"\",baz\"x\"'oar,\"baz\"\"x\"\"',oar\",\"\"\"\",\"\"\",\"\"\",\",\",\\\r\n1,2,3,4,9,10,11,12,13,19,33,22,,,,,,\r\n4,5,6,5,2,3,4,3,1,20,44,33,,,,,,\r\n7,8,9,6,3,4,0,9,4,33,55,33,,,,,,")); dataObject.SetData(DataFormats.CommaSeparatedValue, stream); Clipboard.SetDataObject(dataObject, true); }); interactive.App.ExecuteCommand("Edit.Paste"); interactive.WaitForText( ">[", ". ['abc,', '\"fob\"', '\"fob,\"', 'oar', 'baz\"x\"oar', 'baz,\"x,\"oar', None, None, 'oar', ',\",\"', 'baz\"x\"\\'oar', 'baz\"x\"\\',oar', '\"\"\"\"', '\",\"', ',', '\\\\'],", ". [1, 2, 3, 4, 9, 10, 11, 12, 13, 19, 33, 22, None, None, None, None, None, None],", ". [4, 5, 6, 5, 2, 3, 4, 3, 1, 20, 44, 33, None, None, None, None, None, None],", ". [7, 8, 9, 6, 3, 4, 0, 9, 4, 33, 55, 33, None, None, None, None, None, None],", ".]", "." ); } }
private void AddToolStrip() { var toolStrip = new ToolStrip(); //ts.SuspendLayout(); ToolStripButton button; button = new ToolStripButton { Text = "保存(&S)" }; button.Click += (s, e) => { SaveImage(OriginBitmap); }; toolStrip.Items.Add(button); //クリップボードにコピー、BMP、PNG両対応版 button = new ToolStripButton { Text = "コピー(&C)" }; toolStrip.Items.Add(button); button.ToolTipText = $"画像をクリップボードにコピーする\n" + $"貼り付け先のアプリによってはアルファ(透明)値が再現されないことがある"; button.Click += (s, e) => { //DataObjectに入れたいデータを入れて、それをクリップボードにセットする var data = new System.Windows.DataObject(); //BitmapSource形式そのままでセット data.SetData(typeof(BitmapSource), OriginBitmapSource); //PNG形式にエンコードしたものをMemoryStreamして、それをセット //画像をPNGにエンコード var enc = new PngBitmapEncoder(); enc.Frames.Add(BitmapFrame.Create(OriginBitmapSource)); //エンコードした画像をMemoryStreamにSava using (var ms = new MemoryStream()) { enc.Save(ms); data.SetData("PNG", ms); //クリップボードにセット System.Windows.Clipboard.SetDataObject(data, true); } }; //クリップボードにコピー、BMP版、アルファ値が255になる button = new ToolStripButton { Text = "特殊コピー(&D)" }; button.Click += (s, e) => { System.Windows.Forms.Clipboard.SetImage(OriginBitmap); }; //button.Click += (s, e) => { System.Windows.Clipboard.SetImage(OriginBitmapSource); };//アルファ値が失われる //button.Click += (s, e) => { Image2Clipboard(); }; toolStrip.Items.Add(button); button.ToolTipText = $"アルファ(透明)値を255(不透明に)して画像をクリップボードにコピーする"; //var b3 = new ToolStripButton { Text = "x2" }; //b3.Click += (e, x) => { Scale2(); }; //ts.Items.Add(b3); button = new ToolStripButton { Text = "ウィンドウに合わせて表示(&Z)" }; button.Click += (e, x) => { MyPictureBox.SizeMode = PictureBoxSizeMode.Zoom; MyPictureBox.Dock = DockStyle.Fill; }; toolStrip.Items.Add(button); button = new ToolStripButton { Text = "実寸表示(&A)" }; button.Click += (o, e) => { MyPictureBox.SizeMode = PictureBoxSizeMode.AutoSize; MyPictureBox.Dock = DockStyle.None; }; toolStrip.Items.Add(button); button = new ToolStripButton { Text = "背景黒(&B)" }; button.Click += (s, e) => { MyForm.BackColor = System.Drawing.Color.Black; }; toolStrip.Items.Add(button); button = new ToolStripButton { Text = "背景白(&H)" }; button.Click += (s, e) => { MyForm.BackColor = System.Drawing.Color.White; }; toolStrip.Items.Add(button); button = new ToolStripButton { Text = "閉じる(&W)" }; button.Click += (s, e) => { MyForm.Close(); }; toolStrip.Items.Add(button); //ts.ResumeLayout(false); //ts.PerformLayout(); MyForm.Controls.Add(toolStrip); MyPictureBox = new PictureBox { SizeMode = PictureBoxSizeMode.AutoSize }; var p = new Panel { AutoScroll = true, Dock = DockStyle.Fill }; p.Controls.Add(MyPictureBox); MyForm.Controls.Add(p); MyPictureBox.Image = OriginBitmap; p.BringToFront(); }
private void CopyToClipboard(string[] filePath) { System.Windows.DataObject dataObject = new System.Windows.DataObject(); dataObject.SetData(System.Windows.DataFormats.FileDrop, filePath); System.Windows.Clipboard.SetDataObject(dataObject, true); }
private void CopyToClipboard(BufferBlock[] blocks, bool includeRepl) { _testClipboard.Clear(); var data = new DataObject(); var builder = new StringBuilder(); foreach (var block in blocks) { builder.Append(block.Content); } var text = builder.ToString(); data.SetData(DataFormats.UnicodeText, text); data.SetData(DataFormats.StringFormat, text); if (includeRepl) { data.SetData(InteractiveWindow.ClipboardFormat, BufferBlock.Serialize(blocks)); } _testClipboard.SetDataObject(data, false); }
void OnPaste(object sender, DataObjectPastingEventArgs e) { System.Windows.DataObject d = new System.Windows.DataObject(); d.SetData(System.Windows.DataFormats.Text, e.DataObject.GetData(typeof(string)).ToString().Replace(Environment.NewLine, " ")); e.DataObject = d; }