public static void CopyToClipboard(GUI.WorksheetController dg) { Altaxo.Data.DataTable dt = dg.DataTable; System.Windows.Forms.DataObject dao = new System.Windows.Forms.DataObject(); if (dg.AreDataCellsSelected) { WriteAsciiToClipBoardIfDataCellsSelected(dg, dao); } else if (dg.ArePropertyCellsSelected && !(dg.AreDataCellsSelected)) { WriteAsciiToClipBoardIfOnlyPropertyCellsSelected(dg, dao); } if (dg.AreColumnsOrRowsSelected) { // copy the data as table with the selected columns Altaxo.Data.DataTable.ClipboardMemento tablememento = new Altaxo.Data.DataTable.ClipboardMemento( dg.DataTable, dg.SelectedDataColumns, dg.SelectedDataRows, dg.SelectedPropertyColumns, dg.SelectedPropertyRows); dao.SetData("Altaxo.Data.DataTable.ClipboardMemento", tablememento); // now copy the data object to the clipboard System.Windows.Forms.Clipboard.SetDataObject(dao, true); } }
private void GetClipboardData() { System.Windows.Forms.IDataObject iData = new System.Windows.Forms.DataObject(); try { iData = System.Windows.Forms.Clipboard.GetDataObject(); } catch (System.Runtime.InteropServices.ExternalException externEx) { // Copying a field definition in Access 2002 causes this sometimes? Debug.WriteLine("InteropServices.ExternalException: {0}", externEx.Message); return; } catch (Exception ex) { MessageBox.Show(ex.ToString()); return; } if (iData.GetDataPresent(DataFormats.Text)) { MessageBox.Show((string)iData.GetData(DataFormats.Text)); } }
public virtual void SetClipboardData(System.Windows.Forms.DataObject data) { if (Closed) { throw new InvalidOperationException("Window has been closed"); } InvokeAction(new Action(() => { for (int i = 0; i < 10; i++) { try { ignoreCbChange = true; System.Windows.Forms.Clipboard.SetDataObject(data, true); //If we copied an image, we need to dispose of it... if (data.ContainsImage()) { ISLogger.Write("Disposing image"); Image img = data.GetImage(); img.Dispose(); } return; }catch (Exception ex) { Thread.Sleep(25); } } ISLogger.Write("Failed to set clipboard data!"); })); }
public void EhView_CopyParameterNVV() { System.Windows.Forms.DataObject dao = new System.Windows.Forms.DataObject(); Altaxo.Data.TextColumn txt = new Altaxo.Data.TextColumn(); Altaxo.Data.DoubleColumn col = new Altaxo.Data.DoubleColumn(); Altaxo.Data.DoubleColumn var = new Altaxo.Data.DoubleColumn(); for (int i = 0; i < _doc.CurrentParameters.Count; i++) { txt[i] = _doc.CurrentParameters[i].Name; col[i] = _doc.CurrentParameters[i].Parameter; var[i] = _doc.CurrentParameters[i].Variance; } Altaxo.Data.DataTable tb = new Altaxo.Data.DataTable(); tb.DataColumns.Add(txt, "Name", Altaxo.Data.ColumnKind.V, 0); tb.DataColumns.Add(col, "Value", Altaxo.Data.ColumnKind.V, 0); tb.DataColumns.Add(var, "Variance", Altaxo.Data.ColumnKind.V, 0); Altaxo.Worksheet.Commands.EditCommands.WriteAsciiToClipBoardIfDataCellsSelected( tb, new Altaxo.Collections.AscendingIntegerCollection(), new Altaxo.Collections.AscendingIntegerCollection(), new Altaxo.Collections.AscendingIntegerCollection(), dao); System.Windows.Forms.Clipboard.SetDataObject(dao, true); }
/// <summary> /// Copies the current graph as an bitmap image to the clipboard. /// </summary> /// <param name="ctrl">Controller controlling the current graph.</param> /// <param name="dpiResolution">Resolution of the bitmap in dpi. Determines the pixel size of the bitmap.</param> /// <param name="backbrush">Brush used to fill the background of the image. Can be <c>null</c>.</param> /// <param name="pixelformat">Specify the pixelformat here.</param> public static void CopyPageToClipboardAsBitmap(GraphController ctrl, int dpiResolution, Brush backbrush, PixelFormat pixelformat) { System.Windows.Forms.DataObject dao = new System.Windows.Forms.DataObject(); System.Drawing.Bitmap bitmap = Altaxo.Graph.Procedures.Export.SaveAsBitmap(ctrl.Doc, dpiResolution, backbrush, pixelformat); dao.SetImage(bitmap); System.Windows.Forms.Clipboard.SetDataObject(dao); }
public void CopyToClipboard() { var format = System.Windows.Forms.DataFormats.GetFormat(this.GetType().FullName); System.Windows.Forms.IDataObject dataObject = new System.Windows.Forms.DataObject(); dataObject.SetData(format.Name, false, UtilitiesIO.SaveObjectToJsonString <SceneItem>(this)); Clipboard.SetDataObject(dataObject, false); }
protected override void Work() { var obj = new System.Windows.Forms.DataObject( _format, _data ); Clipboard.SetDataObject(obj, true); }
private string RtfToHtml(string strRTF) { //Declare a Word Application Object and a Word WdSaveOptions object Microsoft.Office.Interop.Word.Application myWord; Object oDoNotSaveChanges = Word.WdSaveOptions.wdDoNotSaveChanges; //Declare two strings to handle the data string sReturnString = string.Empty; string sConvertedString = string.Empty; try { //Instantiate the Word application, //set visible to false and create a document myWord = new Microsoft.Office.Interop.Word.Application(); myWord.Visible = false; myWord.Documents.Add(); // Create a DataObject to hold the Rich Text //and copy it to the clipboard System.Windows.Forms.DataObject doRTF = new System.Windows.Forms.DataObject(); doRTF.SetData("Rich Text Format", strRTF); Clipboard.SetDataObject(doRTF); // 'Paste the contents of the clipboard to the empty, //'hidden Word Document myWord.Windows[1].Selection.Paste(); // '…then, select the entire contents of the document //'and copy back to the clipboard myWord.Windows[1].Selection.WholeStory(); myWord.Windows[1].Selection.Copy(); // 'Now retrieve the HTML property of the DataObject //'stored on the clipboard sConvertedString = Clipboard.GetData(System.Windows.Forms.DataFormats.Html).ToString(); // Remove some leading text that shows up in some instances // '(like when you insert it into an email in Outlook sConvertedString = sConvertedString.Substring(sConvertedString.IndexOf("<html")); // 'Also remove multiple  characters that somehow end up in there sConvertedString = sConvertedString.Replace("Â", ""); //'…and you're done. sReturnString = sConvertedString; if (myWord != null) { myWord.Documents[1].Close(oDoNotSaveChanges); ((Word._Application)myWord).Quit(oDoNotSaveChanges); myWord = null; } } catch (Exception ex) { MessageBox.Show("Error converting Rich Text to HTML: " + ex.Message); } string fileName = Environment.CurrentDirectory + "\\test.htm"; File.WriteAllText(fileName, sReturnString); return(sReturnString); }
/// <summary> /// Load the data from a Tab delimited string of data. Each column is separated by a Tab and each row by a LineFeed character. /// </summary> public void LoadData(string data) { mSourceGrid = null; StringToData(data, out mSourceRange, out mSourceValues); mClipboardDataObject = new System.Windows.Forms.DataObject(); mClipboardDataObject.SetData(RANGEDATA_FORMAT, this); mClipboardDataObject.SetData(typeof(string), StringArrayToString(mSourceValues as string[, ])); }
private static void Restore(List <ClipboardItem> backup) { var data = new System.Windows.Forms.DataObject(); backup.ForEach(item => { data.SetData(item.Format, JsonConvert.DeserializeObject(item.ObjectJson, item.ObjectType)); }); System.Windows.Forms.Clipboard.SetDataObject(data, copy: true); }
/// <summary> /// Load the data from a Tab delimited string of data. Each column is separated by a Tab and each row by a LineFeed character. /// </summary> public void LoadData(string data) { mSourceGrid = null; mCutMode = CutMode.None; mStartDragPosition = new Position(0, 0); StringToData(data, out mSourceRange, out mSourceValues); mClipboardDataObject = new System.Windows.Forms.DataObject(); mClipboardDataObject.SetData(RANGEDATA_FORMAT, this); mClipboardDataObject.SetData(typeof(string), DataToString(mSourceValues, mSourceRange)); }
public void CopyScriptToClipboard() { var data = new System.Windows.Forms.DataObject(); Thread thread; data.SetData(System.Windows.Forms.DataFormats.UnicodeText, true, RecordedScript); thread = new Thread(() => System.Windows.Forms.Clipboard.SetDataObject(data, true)); thread.SetApartmentState(ApartmentState.STA); thread.Start(); thread.Join(); }
/// <summary> /// Test generate rtf text and copy to windows clipboard /// after execute this function , you can paste rtf text in MS Word /// </summary> internal static void TestClipboard() { System.IO.StringWriter myStr = new System.IO.StringWriter(); RTFWriter w = new RTFWriter(myStr); TestBuildRTF(w); w.Close(); System.Windows.Forms.DataObject data = new System.Windows.Forms.DataObject(); data.SetData(System.Windows.Forms.DataFormats.Rtf, myStr.ToString()); System.Windows.Forms.Clipboard.SetDataObject(data, true); System.Windows.Forms.MessageBox.Show("OK, you can paste words in MS Word."); }
/// <summary> /// Load the specified range data into a string array. This method use the cell editor to get the value. /// </summary> /// <param name="sourceGrid"></param> /// <param name="sourceRange"></param> /// <param name="startDragPosition">Starting drag position. Used only for calculating drop destination range.</param> /// <param name="cutMode">Cut mode. Can be used to remove the data from the source when pasting it to the destination or immediately.</param> public void LoadData(GridVirtual sourceGrid, Range sourceRange, Position startDragPosition, CutMode cutMode) { mSourceGrid = sourceGrid; mCutMode = cutMode; mStartDragPosition = startDragPosition; mSourceRange = sourceRange; mSourceValues = new string[mSourceRange.RowsCount, mSourceRange.ColumnsCount]; int arrayRow = 0; for (int r = mSourceRange.Start.Row; r <= mSourceRange.End.Row; r++, arrayRow++) { int arrayCol = 0; for (int c = mSourceRange.Start.Column; c <= mSourceRange.End.Column; c++, arrayCol++) { Position posCell = new Position(r, c); Cells.ICellVirtual cell = sourceGrid.GetCell(posCell); CellContext cellContext = new CellContext(sourceGrid, posCell, cell); if (cell != null && cell.Editor != null) { mSourceValues[arrayRow, arrayCol] = cell.Editor.ValueToString(cell.Model.ValueModel.GetValue(cellContext)); } else if (cell != null) { mSourceValues[arrayRow, arrayCol] = cellContext.GetDisplayText(); } } } //Cut Data if (CutMode == CutMode.CutImmediately && sourceGrid != null) { for (int sr = sourceRange.Start.Row; sr <= sourceRange.End.Row; sr++) { for (int sc = sourceRange.Start.Column; sc <= sourceRange.End.Column; sc++) { Position pos = new Position(sr, sc); Cells.ICellVirtual cell = sourceGrid.GetCell(sr, sc); CellContext cellContext = new CellContext(sourceGrid, pos, cell); if (cell.Editor != null) { cell.Editor.ClearCell(cellContext); } } } } mClipboardDataObject = new System.Windows.Forms.DataObject(); mClipboardDataObject.SetData(RANGEDATA_FORMAT, this); mClipboardDataObject.SetData(typeof(string), DataToString(mSourceValues, mSourceRange)); }
/// <summary> /// Converts a window dataobject to an inputshare clipboard data object /// </summary> /// <param name="data"></param> /// <param name="attempt"></param> /// <returns></returns> public static ClipboardDataBase ConvertToGeneric(System.Windows.Forms.IDataObject data, int attempt = 0) { try { System.Windows.Forms.DataObject obj = data as System.Windows.Forms.DataObject; if (data.GetDataPresent(DataFormats.Bitmap, true)) { using (Image i = obj.GetImage()) { using (MemoryStream ms = new MemoryStream()) { i.Save(ms, Settings.ImageEncodeFormat); return(new ClipboardImageData(ms.ToArray(), true)); } } } else if (data.GetDataPresent(DataFormats.Text)) { return(new ClipboardTextData((string)data.GetData(DataFormats.UnicodeText))); } else if (data.GetDataPresent(DataFormats.FileDrop)) { return(ReadFileDrop(data)); } else { ISLogger.Write("possible data formats: "); foreach (var format in data.GetFormats()) { ISLogger.Write(format); } throw new ClipboardTranslationException("Dataobject not implemented"); } } catch (COMException ex) { ISLogger.Write("COM exception: " + ex.Message); Thread.Sleep(25); if (attempt > 10) { throw new Exception("Could not read clipboard after 10 attempts."); } int n = attempt + 1; return(ConvertToGeneric(data, n)); } }
public static void SetClipboardData(IDictionary <string, object> Dictionary) { try { System.Windows.Forms.IDataObject dataObject = new System.Windows.Forms.DataObject(); foreach (var kvp in Dictionary) { dataObject.SetData(kvp.Key, kvp.Value); } System.Windows.Forms.Clipboard.SetDataObject(dataObject); } catch (Exception) { } }
/// <summary> /// Converts a window dataobject to an inputshare clipboard data object /// </summary> /// <param name="data"></param> /// <param name="attempt"></param> /// <returns></returns> public static ClipboardDataBase ConvertToGeneric(System.Windows.Forms.IDataObject data, int attempt = 0) { try { System.Windows.Forms.DataObject obj = data as System.Windows.Forms.DataObject; if (data.GetDataPresent(DataFormats.Bitmap, true)) { using (Image i = obj.GetImage()) { using (MemoryStream ms = new MemoryStream()) { i.Save(ms, ImageFormat.Jpeg); return(new ClipboardImageData(ms.ToArray(), true)); } } } else if (data.GetDataPresent(DataFormats.Text)) { return(new ClipboardTextData((string)data.GetData(DataFormats.Text))); } else if (data.GetDataPresent(DataFormats.FileDrop)) { ClipboardVirtualFileData fd = ReadFileDrop(data); return(fd); } else { ISLogger.Write("Debug: Could not translate dataobject: type is not implemented"); return(null); } } catch (COMException ex) { ISLogger.Write("COM exception: " + ex.Message); Thread.Sleep(25); if (attempt > 10) { throw new Exception("Could not read clipboard after 10 attempts."); } int n = attempt + 1; return(ConvertToGeneric(data, n)); } }
public static void PasteFromClipboard(GUI.WorksheetController dg) { Altaxo.Data.DataTable dt = dg.DataTable; System.Windows.Forms.DataObject dao = System.Windows.Forms.Clipboard.GetDataObject() as System.Windows.Forms.DataObject; string[] formats = dao.GetFormats(); System.Diagnostics.Trace.WriteLine("Available formats:"); //foreach(string format in formats) System.Diagnostics.Trace.WriteLine(format); if (dao.GetDataPresent("Altaxo.Data.DataTable.ClipboardMemento")) { Altaxo.Data.DataTable.ClipboardMemento tablememento = (Altaxo.Data.DataTable.ClipboardMemento)dao.GetData("Altaxo.Data.DataTable.ClipboardMemento"); PasteFromTable(dg, tablememento.DataTable); return; } object clipboardobject = null; Altaxo.Data.DataTable table = null; if (dao.GetDataPresent("Csv")) { clipboardobject = dao.GetData("Csv"); } else if (dao.GetDataPresent("Text")) { clipboardobject = dao.GetData("Text"); } if (clipboardobject is System.IO.MemoryStream) { table = Altaxo.Serialization.Ascii.AsciiImporter.Import((System.IO.Stream)clipboardobject); } else if (clipboardobject is string) { table = Altaxo.Serialization.Ascii.AsciiImporter.Import((string)clipboardobject); } if (null != table) { PasteFromTable(dg, table); } }
public static void CopyText(string text) { #if WINDOWS Debug.Assert(text.Length != 0); var dataObject = new System.Windows.Forms.DataObject(); dataObject.SetText(text); try { System.Windows.Forms.Clipboard.SetDataObject(dataObject, true, 100, 10); } catch (Exception) { } #else AppKit.NSPasteboard.GeneralPasteboard.ClearContents(); AppKit.NSPasteboard.GeneralPasteboard.SetDataForType(Foundation.NSData.FromString(text), AppKit.NSPasteboard.NSStringType); #endif }
// // /// <summary> // /// 是否可以向操作系统剪切板设置文本 // /// </summary> // /// <returns></returns> // public static bool CanSetText() // { // return true; // } /// <summary> /// 向操作系统剪切板设置文本数据 /// </summary> /// <param name="strText">文本数据</param> /// <returns>操作是否成功</returns> public static bool SetTextToClipboard(string strText) { if (strText != null && strText.Length > 0) { try { System.Windows.Forms.DataObject dataObject = new System.Windows.Forms.DataObject(); dataObject.SetData(System.Windows.Forms.DataFormats.UnicodeText, true, strText); System.Windows.Forms.Clipboard.SetDataObject(dataObject, true); return(true); } catch (Exception e) { Console.WriteLine("Got exception while Copy text to clipboard : " + e); } } return(false); }
private static async Task <bool> ProcessFileDropAsync(System.Windows.Forms.DataObject dataobject) { // get the internal ole dataobject FieldInfo innerDataField = dataobject.GetType().GetField("innerData", BindingFlags.NonPublic | BindingFlags.Instance); var oledataobject = (System.Windows.Forms.IDataObject)innerDataField.GetValue(dataobject); var type = oledataobject.GetType(); if (type.Name == "OleConverter") { // get the COM-object from the OleConverter FieldInfo innerDataField2 = type.GetField("innerData", BindingFlags.NonPublic | BindingFlags.Instance); var item = innerDataField2.GetValue(oledataobject); var asyncitem = item as IDataObjectAsyncCapability; if (asyncitem != null) { var isasync = 0; asyncitem.GetAsyncMode(out isasync); if (isasync != 0) { var task = Task.Run(() => { asyncitem.StartOperation(null); // calling GetData after StartOperation will trigger the download in Chrome // subsequent calls to GetData return cached data // files are downloaded to something like c:\temp\chrome_drag1234_123456789\yourfilename.here var result = dataobject.GetData("FileDrop"); asyncitem.EndOperation(0, null, 1); // DROPEFFECT_COPY = 1 }); await task; return(true); } } } return(false); }
public void GetHTMLTest2() { var datatable = new System.Data.DataTable(); datatable.Columns.Add("Col1", typeof(string)); datatable.Columns.Add("Co12", typeof(string)); datatable.Rows.Add("A", "ł"); datatable.Rows.Add("ą", "ä"); bool write_col_headers = true; string tsv = Isotope.Data.DataExporter.ToTSVString(datatable, write_col_headers); string in_html = Isotope.Data.DataExporter.ToHTMLString(datatable, write_col_headers); string failure = null; var thread = new System.Threading.Thread(() => { System.Windows.Forms.Clipboard.Clear(); string cf_html = Isotope.Clipboard.HTMLCLipboardData.GetCFHTMLString( in_html, null, null); var dataobject = new System.Windows.Forms.DataObject(); // System.Windows.Forms.Clipboard.GetDataObject(); dataobject.SetData(System.Windows.Forms.DataFormats.Text, tsv); dataobject.SetData(System.Windows.Forms.DataFormats.Html, cf_html); System.Windows.Forms.Clipboard.SetDataObject(dataobject, true); var out_html = Isotope.Clipboard.ClipboardUtil.GetHTML(); if (out_html != in_html) { failure = "fail"; } }); thread.SetApartmentState(System.Threading.ApartmentState.STA); thread.Start(); thread.Join(); if (failure != null) { Assert.Fail(); } }
public static async Task <StringCollection> GetFileDrop(System.Windows.Forms.DataObject dataobject) { if (dataobject.ContainsFileDropList()) { var files = dataobject.GetFileDropList(); if (files.Count == 0) { // try async version if (await ProcessFileDropAsync(dataobject)) { files = dataobject.GetFileDropList(); } } return(files); } return(null); }
public static void SetDataEx(this IDataObject dataObject, string format, object data) { System.Windows.Forms.DataFormats.Format dataFormat = System.Windows.Forms.DataFormats.GetFormat(format); // Initialize the format structure FORMATETC 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; // Use a temporary standard data object to convert from managed to native. System.Windows.Forms.DataObject conv = new System.Windows.Forms.DataObject(); conv.SetData(format, true, data); STGMEDIUM medium; ((IDataObject)conv).GetData(ref formatETC, out medium); try { ((IDataObject)dataObject).SetData(ref formatETC, ref medium, true); } catch { Win32.ReleaseStgMedium(ref medium); throw; } } else { SetManagedData((IDataObject)dataObject, format, data); } }
/* * [DllImport("user32.dll")] * static extern bool OpenClipboard(IntPtr hWndNewOwner); * [DllImport("user32.dll")] * static extern bool EmptyClipboard(); * [DllImport("user32.dll")] * static extern IntPtr SetClipboardData(uint uFormat, IntPtr hMem); * [DllImport("user32.dll")] * static extern bool CloseClipboard(); * [DllImport("gdi32.dll")] * static extern IntPtr CopyEnhMetaFile(IntPtr hemfSrc, IntPtr hNULL); * [DllImport("gdi32.dll")] * static extern bool DeleteEnhMetaFile(IntPtr hemf); * * /// <summary> * /// Microsoft Knowledge Base Article - 323530 PRB: Metafiles on Clipboard Are Not Visible to All Applications * /// </summary> * /// <param name="hWnd"></param> * /// <param name="mf"></param> * /// <returns></returns> * static bool PutEnhMetafileOnClipboard(IntPtr hWnd, Metafile mf) * { * bool bResult = false; * IntPtr hEMF, hEMF2; * hEMF = mf.GetHenhmetafile(); // invalidates mf * if (!hEMF.Equals(new IntPtr(0))) * { * hEMF2 = CopyEnhMetaFile(hEMF, new IntPtr(0)); * if (!hEMF2.Equals(new IntPtr(0))) * { * if (OpenClipboard(hWnd)) * { * if (EmptyClipboard()) * { * IntPtr hRes = SetClipboardData(14 , hEMF2); // 14==CF_ENHMETAFILE * bResult = hRes.Equals(hEMF2); * CloseClipboard(); * } * } * } * DeleteEnhMetaFile(hEMF); * } * return bResult; * } */ static public void Run(GraphController ctrl) { // System.Drawing.Imaging.Metafile mf = Altaxo.Graph.Procedures.Export.GetMetafile(ctrl.Doc); // PutEnhMetafileOnClipboard(ctrl.View.Form.Handle, mf); System.Windows.Forms.DataObject dao = new System.Windows.Forms.DataObject(); string filepath = System.IO.Path.GetTempPath(); string filename = filepath + "AltaxoClipboardMetafile.emf"; if (System.IO.File.Exists(filename)) { System.IO.File.Delete(filename); } Metafile mf = Altaxo.Graph.Procedures.Export.SaveAsMetafile(ctrl.Doc, filename, 300); System.Collections.Specialized.StringCollection coll = new System.Collections.Specialized.StringCollection(); coll.Add(filename); dao.SetFileDropList(coll); dao.SetData(typeof(Metafile), mf); System.Windows.Forms.Clipboard.SetDataObject(dao); }
public void IzradaExcel(System.Windows.Forms.DataObject podatci) { Application xlexcel; Workbook xlworkbook; Worksheet xlworksheet; object _misValue = System.Reflection.Missing.Value; xlexcel = new Application { Visible = true }; xlworkbook = xlexcel.Workbooks.Add(_misValue); xlworksheet = (Worksheet)xlworkbook.Worksheets.get_Item(1); Range Celije = xlworkbook.Worksheets[1].Cells; Celije.NumberFormat = "@"; Range CR = (Range)xlworksheet.Cells[1, 1]; CR.Select(); xlworksheet.PasteSpecial(CR, XlPasteType.xlPasteValues, Type.Missing, Type.Missing, Type.Missing, Type.Missing, true); }
/// <summary> /// Execute the command /// </summary> public void Exec() { ElementGroup elementGroup = new ElementGroup(_store); bool foundSome = false; foreach (object o in _elements) { // Pick out shapes representing Component model elements. ShapeElement element = o as ShapeElement; if (element != null && element.ModelElement != null || o is ModelElement) { ModelElement mel = element != null ? element.ModelElement : o as ModelElement; if (mel is Entity || mel is Operation || mel is Enumeration || mel is ClassImplementation || mel is ServiceContract || mel is Property) { // add the element and its embedded children to the group elementGroup.AddGraph(mel, true); foundSome = true; } } } if (!foundSome) { return; } // A DataObject carries a serialized version. System.Windows.Forms.IDataObject data = new System.Windows.Forms.DataObject(); data.SetData(elementGroup.CreatePrototype()); System.Windows.Forms.Clipboard.SetDataObject (data, // serialized clones of our selected model elements false, // we don’t want to export outside this application 10, // retry 10 times on failure 50); // waiting 50ms between retries }
public override void ConvertToNetDataObjectAndPutToClipboard() { var result = new System.Windows.Forms.DataObject(); if (null != _graphDocumentMetafileImage) { result.SetImage(_graphDocumentMetafileImage); } else if (null != _graphDocumentBitmapImage) { result.SetImage(_graphDocumentBitmapImage); } if (!string.IsNullOrEmpty(_graphDocumentDropdownFileName)) { var coll = new System.Collections.Specialized.StringCollection(); EnsureDropFileCreated(); coll.Add(_graphDocumentDropdownFileName); result.SetFileDropList(coll); } System.Windows.Forms.Clipboard.SetDataObject(result, true); }
public void GetHTMLTest2() { var datatable = new System.Data.DataTable(); datatable.Columns.Add("Col1", typeof (string)); datatable.Columns.Add("Co12", typeof (string)); datatable.Rows.Add("A", "ł"); datatable.Rows.Add("ą", "ä"); bool write_col_headers = true; string tsv = Isotope.Data.DataExporter.ToTSVString(datatable, write_col_headers); string in_html = Isotope.Data.DataExporter.ToHTMLString(datatable, write_col_headers); string failure = null; var thread = new System.Threading.Thread(() => { System.Windows.Forms.Clipboard.Clear(); string cf_html = Isotope.Clipboard.HTMLCLipboardData.GetCFHTMLString( in_html, null, null); var dataobject = new System.Windows.Forms.DataObject(); // System.Windows.Forms.Clipboard.GetDataObject(); dataobject.SetData(System.Windows.Forms.DataFormats.Text, tsv); dataobject.SetData(System.Windows.Forms.DataFormats.Html, cf_html); System.Windows.Forms.Clipboard.SetDataObject(dataobject, true); var out_html = Isotope.Clipboard.ClipboardUtil.GetHTML(); if (out_html != in_html) { failure = "fail"; } }); thread.SetApartmentState(System.Threading.ApartmentState.STA); thread.Start(); thread.Join(); if (failure != null) { Assert.Fail(); } }
/// <summary> /// Test generate rtf text and copy to windows clipboard /// after execute this function , you can paste rtf text in MS Word /// </summary> internal static void TestClipboard() { System.IO.StringWriter myStr = new System.IO.StringWriter(); RTFWriter w = new RTFWriter( myStr ); TestBuildRTF( w ); w.Close(); System.Windows.Forms.DataObject data = new System.Windows.Forms.DataObject(); data.SetData( System.Windows.Forms.DataFormats.Rtf , myStr.ToString()); System.Windows.Forms.Clipboard.SetDataObject( data , true ); System.Windows.Forms.MessageBox.Show("OK, you can paste words in MS Word."); }
/// <summary> /// Load the specified range data into a string array. This method use the cell editor to get the value. /// </summary> /// <param name="sourceGrid"></param> /// <param name="sourceRange"></param> /// <param name="startDragPosition">Starting drag position. Used only for calculating drop destination range.</param> /// <param name="cutMode">Cut mode. Can be used to remove the data from the source when pasting it to the destination or immediately.</param> public void LoadData(GridVirtual sourceGrid, Range sourceRange, Position startDragPosition, CutMode cutMode) { mSourceGrid = sourceGrid; mCutMode = cutMode; mStartDragPosition = startDragPosition; mSourceRange = sourceRange; mSourceValues = new string[mSourceRange.RowsCount, mSourceRange.ColumnsCount]; int arrayRow = 0; for (int r = mSourceRange.Start.Row; r <= mSourceRange.End.Row; r++, arrayRow++) { int arrayCol = 0; for (int c = mSourceRange.Start.Column; c <= mSourceRange.End.Column; c++, arrayCol++) { Position posCell = new Position(r, c); Cells.ICellVirtual cell = sourceGrid.GetCell(posCell); CellContext cellContext = new CellContext(sourceGrid, posCell, cell); if (cell != null && cell.Editor != null && cell.Editor.IsStringConversionSupported()) mSourceValues[arrayRow, arrayCol] = cell.Editor.ValueToString( cell.Model.ValueModel.GetValue(cellContext) ); else if (cell != null) mSourceValues[arrayRow, arrayCol] = cellContext.DisplayText; } } //Cut Data if (CutMode == CutMode.CutImmediately && sourceGrid != null) { sourceGrid.ClearValues(new RangeRegion(sourceRange)); //for (int sr = sourceRange.Start.Row; sr <= sourceRange.End.Row; sr++) // for (int sc = sourceRange.Start.Column; sc <= sourceRange.End.Column; sc++) // { // Position pos = new Position(sr, sc); // Cells.ICellVirtual cell = sourceGrid.GetCell(sr, sc); // CellContext cellContext = new CellContext(sourceGrid, pos, cell); // if (cell.Editor != null) // cell.Editor.ClearCell(cellContext); // } } mClipboardDataObject = new System.Windows.Forms.DataObject(); mClipboardDataObject.SetData(RANGEDATA_FORMAT, this); mClipboardDataObject.SetData(typeof(string), DataToString(mSourceValues, mSourceRange)); }
private void newt_GiveFeedback(object sender, GiveFeedbackEventArgs e) { e.Handled = true; e.UseDefaultCursors = true; if (this._TabDropData == null) return; var doo = new WIN.Forms.DataObject(this._TabDropData); if (doo.GetDataPresent("DragWindow")) { IntPtr hwnd = ShellView.GetIntPtrFromData(doo.GetData("DragWindow")); User32.PostMessage(hwnd, 0x403, IntPtr.Zero, IntPtr.Zero); } else { e.UseDefaultCursors = true; } if (ShellView.IsDropDescriptionValid(this._TabDropData)) { e.UseDefaultCursors = false; Cursor = Cursors.Arrow; } else { e.UseDefaultCursors = true; } if (ShellView.IsShowingLayered(doo)) { e.UseDefaultCursors = false; Cursor = Cursors.Arrow; } else { e.UseDefaultCursors = true; } }
public void EhView_CopyParameterNVV() { System.Windows.Forms.DataObject dao = new System.Windows.Forms.DataObject(); Altaxo.Data.TextColumn txt = new Altaxo.Data.TextColumn(); Altaxo.Data.DoubleColumn col = new Altaxo.Data.DoubleColumn(); Altaxo.Data.DoubleColumn var = new Altaxo.Data.DoubleColumn(); for (int i = 0; i < _doc.CurrentParameters.Count; i++) { txt[i] = _doc.CurrentParameters[i].Name; col[i] = _doc.CurrentParameters[i].Parameter; var[i] = _doc.CurrentParameters[i].Variance; } Altaxo.Data.DataTable tb = new Altaxo.Data.DataTable(); tb.DataColumns.Add(txt, "Name", Altaxo.Data.ColumnKind.V, 0); tb.DataColumns.Add(col, "Value", Altaxo.Data.ColumnKind.V, 0); tb.DataColumns.Add(var, "Variance", Altaxo.Data.ColumnKind.V, 0); Altaxo.Worksheet.Commands.EditCommands.WriteAsciiToClipBoardIfDataCellsSelected( tb, new Altaxo.Collections.AscendingIntegerCollection(), new Altaxo.Collections.AscendingIntegerCollection(), new Altaxo.Collections.AscendingIntegerCollection(), dao); System.Windows.Forms.Clipboard.SetDataObject(dao, true); }
public static void SetDataEx(this IDataObject dataObject, string format, object data) { System.Windows.Forms.DataFormats.Format dataFormat = System.Windows.Forms.DataFormats.GetFormat(format); // Initialize the format structure FORMATETC 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; // Use a temporary standard data object to convert from managed to native. System.Windows.Forms.DataObject conv = new System.Windows.Forms.DataObject(); conv.SetData(format, true, data); STGMEDIUM medium; ((IDataObject)conv).GetData(ref formatETC, out medium); try { ((IDataObject)dataObject).SetData(ref formatETC, ref medium, true); } catch { Win32.ReleaseStgMedium(ref medium); throw; } } else { SetManagedData((IDataObject)dataObject, format, data); } }
/// <summary> /// Copy data and put into Clipboard. /// </summary> public bool Copy() { if (IsEditing) { this.controlAdapter.EditControlCopy(); } else { this.controlAdapter.ChangeCursor(CursorStyle.Busy); try { if (BeforeCopy != null) { var evtArg = new BeforeRangeOperationEventArgs(selectionRange); BeforeCopy(this, evtArg); if (evtArg.IsCancelled) { return(false); } } #if EX_SCRIPT var scriptReturn = RaiseScriptEvent("oncopy"); if (scriptReturn != null && !ScriptRunningMachine.GetBoolValue(scriptReturn)) { return(false); } #endif // EX_SCRIPT // highlight current copy range currentCopingRange = selectionRange; #if WINFORM || WPF DataObject data = new DataObject(); data.SetData(ClipBoardDataFormatIdentify, GetPartialGrid(currentCopingRange, PartialGridCopyFlag.All, ExPartialGridCopyFlag.None, true)); string text = StringifyRange(currentCopingRange); if (!string.IsNullOrEmpty(text)) { data.SetText(text); } // set object data into clipboard Clipboard.SetDataObject(data); #endif // WINFORM || WPF if (AfterCopy != null) { AfterCopy(this, new RangeEventArgs(this.selectionRange)); } } catch (Exception ex) { this.NotifyExceptionHappen(ex); return(false); } finally { this.controlAdapter.ChangeCursor(CursorStyle.PlatformDefault); } } return(true); }
/* [DllImport("user32.dll")] static extern bool OpenClipboard(IntPtr hWndNewOwner); [DllImport("user32.dll")] static extern bool EmptyClipboard(); [DllImport("user32.dll")] static extern IntPtr SetClipboardData(uint uFormat, IntPtr hMem); [DllImport("user32.dll")] static extern bool CloseClipboard(); [DllImport("gdi32.dll")] static extern IntPtr CopyEnhMetaFile(IntPtr hemfSrc, IntPtr hNULL); [DllImport("gdi32.dll")] static extern bool DeleteEnhMetaFile(IntPtr hemf); /// <summary> /// Microsoft Knowledge Base Article - 323530 PRB: Metafiles on Clipboard Are Not Visible to All Applications /// </summary> /// <param name="hWnd"></param> /// <param name="mf"></param> /// <returns></returns> static bool PutEnhMetafileOnClipboard(IntPtr hWnd, Metafile mf) { bool bResult = false; IntPtr hEMF, hEMF2; hEMF = mf.GetHenhmetafile(); // invalidates mf if (!hEMF.Equals(new IntPtr(0))) { hEMF2 = CopyEnhMetaFile(hEMF, new IntPtr(0)); if (!hEMF2.Equals(new IntPtr(0))) { if (OpenClipboard(hWnd)) { if (EmptyClipboard()) { IntPtr hRes = SetClipboardData(14 , hEMF2); // 14==CF_ENHMETAFILE bResult = hRes.Equals(hEMF2); CloseClipboard(); } } } DeleteEnhMetaFile(hEMF); } return bResult; } */ static public void Run(GraphController ctrl) { // System.Drawing.Imaging.Metafile mf = Altaxo.Graph.Procedures.Export.GetMetafile(ctrl.Doc); // PutEnhMetafileOnClipboard(ctrl.View.Form.Handle, mf); System.Windows.Forms.DataObject dao = new System.Windows.Forms.DataObject(); string filepath = System.IO.Path.GetTempPath(); string filename = filepath + "AltaxoClipboardMetafile.emf"; if (System.IO.File.Exists(filename)) System.IO.File.Delete(filename); Metafile mf = Altaxo.Graph.Procedures.Export.SaveAsMetafile(ctrl.Doc, filename, 300); System.Collections.Specialized.StringCollection coll = new System.Collections.Specialized.StringCollection(); coll.Add(filename); dao.SetFileDropList(coll); dao.SetData(typeof(Metafile), mf); System.Windows.Forms.Clipboard.SetDataObject(dao); }
private static void DumpScreenToClipboard(int top, int count) { var buffer = ReadBufferLines(top, count); var bufferWidth = _singleton._console.BufferWidth; var textBuffer = new StringBuilder(buffer.Length + count); var rtfBuffer = new StringBuilder(); rtfBuffer.Append(@"{\rtf\ansi{\fonttbl{\f0 Consolas;}}"); var colorTable = GetColorTable(); rtfBuffer.AppendFormat(@"{{\colortbl;{0}}}{1}", colorTable, Environment.NewLine); rtfBuffer.Append(@"\f0 \fs18 "); var charInfo = buffer[0]; var fgColor = (int)charInfo.ForegroundColor; var bgColor = (int)charInfo.BackgroundColor; rtfBuffer.AppendFormat(@"{{\cf{0}\chshdng0\chcbpat{1} ", fgColor + 1, bgColor + 1); for (int i = 0; i < count; i++) { var spaces = 0; var rtfSpaces = 0; for (int j = 0; j < bufferWidth; j++) { charInfo = buffer[i * bufferWidth + j]; if ((int)charInfo.ForegroundColor != fgColor || (int)charInfo.BackgroundColor != bgColor) { if (rtfSpaces > 0) { rtfBuffer.Append(' ', rtfSpaces); rtfSpaces = 0; } fgColor = (int)charInfo.ForegroundColor; bgColor = (int)charInfo.BackgroundColor; rtfBuffer.AppendFormat(@"}}{{\cf{0}\chshdng0\chcbpat{1} ", fgColor + 1, bgColor + 1); } var c = (char)charInfo.UnicodeChar; if (c == ' ') { // Trailing spaces are skipped, we'll add them back if we find a non-space // before the end of line ++spaces; ++rtfSpaces; } else { if (spaces > 0) { textBuffer.Append(' ', spaces); spaces = 0; } if (rtfSpaces > 0) { rtfBuffer.Append(' ', rtfSpaces); rtfSpaces = 0; } textBuffer.Append(c); switch (c) { case '\\': rtfBuffer.Append(@"\\"); break; case '\t': rtfBuffer.Append(@"\tab"); break; case '{': rtfBuffer.Append(@"\{"); break; case '}': rtfBuffer.Append(@"\}"); break; default: rtfBuffer.Append(c); break; } } } rtfBuffer.AppendFormat(@"\shading0 \cbpat{0} \par{1}", bgColor + 1, Environment.NewLine); textBuffer.Append(Environment.NewLine); } rtfBuffer.Append("}}"); #if !CORECLR // TODO: break dependency on Window.Forms w/ p/invokes to clipboard directly, for now, just silently skip the copy. var dataObject = new System.Windows.Forms.DataObject(); dataObject.SetData(System.Windows.Forms.DataFormats.Text, textBuffer.ToString()); dataObject.SetData(System.Windows.Forms.DataFormats.Rtf, rtfBuffer.ToString()); ExecuteOnSTAThread(() => System.Windows.Forms.Clipboard.SetDataObject(dataObject, copy: true)); #endif }
/// <summary> /// Load the data from a Tab delimited string of data. Each column is separated by a Tab and each row by a LineFeed character. /// </summary> public void LoadData(string data) { mSourceGrid = null; StringToData(data, out mSourceRange, out mSourceValues); mClipboardDataObject = new System.Windows.Forms.DataObject(); mClipboardDataObject.SetData(RANGEDATA_FORMAT, this); mClipboardDataObject.SetData(typeof(string), StringArrayToString(mSourceValues as string[,])); }
/// <summary> /// Load the data from a Tab delimited string of data. Each column is separated by a Tab and each row by a LineFeed character. /// </summary> public void LoadData(string data) { mSourceGrid = null; mCutMode = CutMode.None; mStartDragPosition = new Position(0, 0); StringToData(data, out mSourceRange, out mSourceValues); mClipboardDataObject = new System.Windows.Forms.DataObject(); mClipboardDataObject.SetData(RANGEDATA_FORMAT, this); mClipboardDataObject.SetData(typeof(string), DataToString(mSourceValues, mSourceRange)); }
/// <summary> /// Copies the current graph as an bitmap image to the clipboard. /// </summary> /// <param name="ctrl">Controller controlling the current graph.</param> /// <param name="dpiResolution">Resolution of the bitmap in dpi. Determines the pixel size of the bitmap.</param> /// <param name="backbrush">Brush used to fill the background of the image. Can be <c>null</c>.</param> /// <param name="pixelformat">Specify the pixelformat here.</param> public static void CopyPageToClipboardAsBitmap(GraphController ctrl, int dpiResolution, Brush backbrush, PixelFormat pixelformat) { System.Windows.Forms.DataObject dao = new System.Windows.Forms.DataObject(); System.Drawing.Bitmap bitmap = Altaxo.Graph.Procedures.Export.SaveAsBitmap(ctrl.Doc, dpiResolution, backbrush, pixelformat); dao.SetImage(bitmap); System.Windows.Forms.Clipboard.SetDataObject(dao); }
/// <summary> /// Copy data from Clipboard and put on grid. /// /// Currently ReoGrid supports the following types of source from the clipboard. /// - Data from another ReoGrid instance /// - Plain/Unicode Text from any Windows Applications /// - Tabbed Plain/Unicode Data from Excel or similar applications /// /// When data copied from another ReoGrid instance, and the destination range /// is bigger than the source, ReoGrid will try to repeat putting data to fill /// the destination range entirely. /// /// Todo: Copy border and cell style from Excel. /// </summary> public bool Paste() { if (IsEditing) { this.controlAdapter.EditControlPaste(); } else { // Paste method will always perform action to do paste // do nothing if in readonly mode if (this.HasSettings(WorksheetSettings.Edit_Readonly) // or selection is empty || this.selectionRange.IsEmpty) { return(false); } try { this.controlAdapter.ChangeCursor(CursorStyle.Busy); PartialGrid partialGrid = null; string clipboardText = null; #if WINFORM || WPF DataObject data = Clipboard.GetDataObject() as DataObject; if (data != null) { partialGrid = data.GetData(ClipBoardDataFormatIdentify) as PartialGrid; if (data.ContainsText()) { clipboardText = data.GetText(); } } #elif ANDROID #endif // WINFORM || WPF if (partialGrid != null) { #region Partial Grid Pasting int startRow = selectionRange.Row; int startCol = selectionRange.Col; int rows = partialGrid.Rows; int cols = partialGrid.Columns; int rowRepeat = 1; int colRepeat = 1; if (selectionRange.Rows % partialGrid.Rows == 0) { rows = selectionRange.Rows; rowRepeat = selectionRange.Rows / partialGrid.Rows; } if (selectionRange.Cols % partialGrid.Columns == 0) { cols = selectionRange.Cols; colRepeat = selectionRange.Cols / partialGrid.Columns; } var targetRange = new RangePosition(startRow, startCol, rows, cols); if (!RaiseBeforePasteEvent(targetRange)) { return(false); } if (targetRange.EndRow >= this.rows.Count || targetRange.EndCol >= this.cols.Count) { // TODO: paste range overflow // need to notify user-code to handle this return(false); } // check whether the range to be pasted contains readonly cell if (this.CheckRangeReadonly(targetRange)) { this.NotifyExceptionHappen(new OperationOnReadonlyCellException("specified range contains readonly cell")); return(false); } // check any intersected merge-range in partial grid // bool cancelPerformPaste = false; if (partialGrid.Cells != null) { try { #region Check repeated intersected ranges for (int rr = 0; rr < rowRepeat; rr++) { for (int cc = 0; cc < colRepeat; cc++) { partialGrid.Cells.Iterate((row, col, cell) => { if (cell.IsMergedCell) { for (int r = startRow; r < cell.MergeEndPos.Row - cell.InternalRow + startRow + 1; r++) { for (int c = startCol; c < cell.MergeEndPos.Col - cell.InternalCol + startCol + 1; c++) { int tr = r + rr * partialGrid.Rows; int tc = c + cc * partialGrid.Columns; var existedCell = cells[tr, tc]; if (existedCell != null) { if ( // cell is a part of merged cell (existedCell.Rowspan == 0 && existedCell.Colspan == 0) // cell is merged cell || existedCell.IsMergedCell) { throw new RangeIntersectionException(selectionRange); } // cell is readonly else if (existedCell.IsReadOnly) { throw new CellDataReadonlyException(cell.InternalPos); } } } } } return(Math.Min(cell.Colspan, (short)1)); }); } } #endregion // Check repeated intersected ranges } catch (Exception ex) { cancelPerformPaste = true; // raise event to notify user-code there is error happened during paste operation if (OnPasteError != null) { OnPasteError(this, new RangeOperationErrorEventArgs(selectionRange, ex)); } } } if (!cancelPerformPaste) { DoAction(new SetPartialGridAction(new RangePosition( startRow, startCol, rows, cols), partialGrid)); } #endregion // Partial Grid Pasting } else if (!string.IsNullOrEmpty(clipboardText)) { #region Plain Text Pasting var arrayData = RGUtility.ParseTabbedString(clipboardText); int rows = Math.Max(selectionRange.Rows, arrayData.GetLength(0)); int cols = Math.Max(selectionRange.Cols, arrayData.GetLength(1)); var targetRange = new RangePosition(selectionRange.Row, selectionRange.Col, rows, cols); if (!RaiseBeforePasteEvent(targetRange)) { return(false); } if (this.controlAdapter != null) { var actionSupportedControl = this.controlAdapter.ControlInstance as IActionControl; if (actionSupportedControl != null) { actionSupportedControl.DoAction(this, new SetRangeDataAction(targetRange, arrayData)); } } #endregion // Plain Text Pasting } } catch (Exception ex) { // raise event to notify user-code there is error happened during paste operation //if (OnPasteError != null) //{ // OnPasteError(this, new RangeOperationErrorEventArgs(selectionRange, ex)); //} this.NotifyExceptionHappen(ex); } finally { this.controlAdapter.ChangeCursor(CursorStyle.Selection); RequestInvalidate(); } if (AfterPaste != null) { AfterPaste(this, new RangeEventArgs(this.selectionRange)); } } return(true); }
public override void ConvertToNetDataObjectAndPutToClipboard() { var result = new System.Windows.Forms.DataObject(); if (null != _graphDocumentMetafileImage) { result.SetImage(_graphDocumentMetafileImage); } else if (null != _graphDocumentBitmapImage) { result.SetImage(_graphDocumentBitmapImage); } if (!string.IsNullOrEmpty(_graphDocumentDropdownFileName)) { var coll = new System.Collections.Specialized.StringCollection(); EnsureDropFileCreated(); coll.Add(_graphDocumentDropdownFileName); result.SetFileDropList(coll); } System.Windows.Forms.Clipboard.SetDataObject(result, true); }