int IOleDropTarget.OleDragEnter(object pDataObj, int grfKeyState, long pt, ref int pdwEffect) { TraceDebug.Trace("OleDragEnter"); POINT pointl = new POINT(); pointl.x = DropTarget.GetX(pt); pointl.y = DropTarget.GetY(pt); // this shouldn't happen, but seems to occasionally, so rather than an Assertion that // will cause a GPF, we'll try and handle it nicely.... if (lastDataObject != null) { // Drag leave wasn't called, so call it now... this.owner.OnDragLeave(EventArgs.Empty); lastDataObject = null; this.lastEffect = DragDropEffects.None; } DragEventArgs e = this.CreateDragEventArgs(pDataObj, grfKeyState, pointl, pdwEffect); if (e != null) { this.owner.OnDragEnter(e); pdwEffect = (int)e.Effect; this.lastEffect = e.Effect; } else { pdwEffect = 0; } return(0); }
private static void Main(string[] args) { try { System.Windows.Forms.IDataObject content = Clipboard.GetDataObject(); string[] formats = content.GetFormats(); foreach (var f in formats) { Console.WriteLine($"{f}"); } if (Clipboard.ContainsImage()) { var clipboardImage = Clipboard.GetImage(); string imagePath = @"r:\temp\images\png\p1.png"; clipboardImage.Save(imagePath); } } catch (Exception ex) { var fullname = System.Reflection.Assembly.GetEntryAssembly().Location; var progname = Path.GetFileNameWithoutExtension(fullname); Console.Error.WriteLine($"{progname} Error: {ex.Message}"); } }
/// <summary> /// Initializes a new instance of the <see cref="OutlookDataObject"/> class. /// </summary> /// <param name="underlyingDataObject">The underlying data object to wrap.</param> public OutlookDataObject(System.Windows.Forms.IDataObject underlyingDataObject) { //get the underlying dataobject and its ComType IDataObject interface to it this.underlyingDataObject = underlyingDataObject; this.comUnderlyingDataObject = (System.Runtime.InteropServices.ComTypes.IDataObject) this.underlyingDataObject; //get the internal ole dataobject and its GetDataFromHGLOBLAL so it can be called later FieldInfo innerDataField = this.underlyingDataObject.GetType().GetField("innerData", BindingFlags.NonPublic | BindingFlags.Instance); try { this.oleUnderlyingDataObject = (System.Windows.Forms.IDataObject)innerDataField.GetValue(this.underlyingDataObject); } catch (Exception ex) { Console.WriteLine(ex.Message); } try { this.getDataFromHGLOBLALMethod = this.oleUnderlyingDataObject.GetType().GetMethod("GetDataFromHGLOBLAL", BindingFlags.NonPublic | BindingFlags.Instance); } catch (Exception ex) { Console.WriteLine(ex.Message); } }
/// <summary> /// Paste command processing /// </summary> /// <param name="sender">The sender.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> private void OnPaste(object sender, EventArgs e) { Diagram diagram = this.CurrentDocView.CurrentDiagram; if (diagram == null && this.SingleSelection != null) { return; } System.Windows.Forms.IDataObject data = System.Windows.Forms.Clipboard.GetDataObject(); DesignSurfaceElementOperations op = diagram.ElementOperations; if (op.CanMerge(((PresentationElement)this.SingleSelection).ModelElement, data)) { // Find a suitable place to position the new shape. PointD place = new PointD(0, 0); foreach (object item in this.CurrentSelection) { ShapeElement shape = item as ShapeElement; if (shape != null) { place = shape.AbsoluteBoundingBox.Center; break; } } using (Transaction t = diagram.Store.TransactionManager.BeginTransaction("paste")) { // Do the business. op.Merge((PresentationElement)this.SingleSelection, data, PointD.ToPointF(place)); t.Commit(); System.Windows.Forms.Clipboard.Clear(); } } }
//-------------------------------------------------- private Image m_Capture() { try { Clipboard.Clear(); // get the next frame; SendMessage(mCapHwnd, WM_CAP_GET_FRAME, 0, 0); // copy the frame to the clipboard SendMessage(mCapHwnd, WM_CAP_COPY, 0, 0); // paste the frame into the event args image // get from the clipboard tempObj = Clipboard.GetDataObject(); tempImg = (System.Drawing.Bitmap)tempObj.GetData(System.Windows.Forms.DataFormats.Bitmap); //int t1 = DateTime.Now.Millisecond; GC.Collect(); //int t2 = DateTime.Now.Millisecond; //int t = t2 - t1; /* * For some reason, the API is not resizing the video * feed to the width and height provided when the video * feed was started, so we must resize the image here */ //x.WebCamImage = tempImg.GetThumbnailImage(m_Width, m_Height, null, System.IntPtr.Zero); } catch (Exception excep) { MessageBox.Show("An error ocurred while capturing the video image. The video capture will now be terminated.\r\n\n" + excep.Message); Stop(); // stop the process } return(tempImg); }
public static object GetClipboardData() { object ret = null; ThreadStart method = delegate() { System.Windows.Forms.IDataObject dataObject = Clipboard.GetDataObject(); if (dataObject != null && dataObject.GetDataPresent(DataFormats.Text)) { ret = dataObject.GetData(DataFormats.Text); } }; if (Thread.CurrentThread.GetApartmentState() != ApartmentState.STA) { Thread thread = new Thread(method); thread.SetApartmentState(ApartmentState.STA); thread.Start(); thread.Join(); } else { method(); } return(ret); }
/// <include file='doc\OleDataObject.uex' path='docs/doc[@for=OleDataObject.OleDataObject1]/*' /> public OleDataObject(IDataObject winData) : base(winData) { this.oleData = winData as IOleDataObject; if (null == this.oleData) oleData = (IOleDataObject)(new Ole2BclDataObject(this as IComDataObject)); }
private void ClipChanged() { try { System.Windows.Forms.IDataObject iData = Clipboard.GetDataObject(); ClipboardFormat?format = null; foreach (var f in formats) { if (iData.GetDataPresent(f)) { format = (ClipboardFormat)Enum.Parse(typeof(ClipboardFormat), f); break; } } object data = iData.GetData(format.ToString()); if (data == null || format == null) { return; } OnClipboardChange?.Invoke((ClipboardFormat)format, data); if (data is IDisposable disposable) { disposable.Dispose(); } } catch (Exception) { } }
private DragEventArgs CreateDragEventArgs(object pDataObj, int grfKeyState, POINT pt, int pdwEffect) { System.Windows.Forms.IDataObject data = null; if (pDataObj == null) { data = this.lastDataObject; } else if (pDataObj is System.Windows.Forms.IDataObject) { data = (System.Windows.Forms.IDataObject)pDataObj; } else if (pDataObj is System.Runtime.InteropServices.ComTypes.IDataObject) { data = new DataObject(pDataObj); } else { TraceDebug.Trace("CreateDragEventArgs returns null"); return(null); } DragEventArgs args = new DragEventArgs(data, grfKeyState, pt.x, pt.y, (DragDropEffects)pdwEffect, this.lastEffect); this.lastDataObject = data; return(args); }
/// <summary> /// Registers a Control as a drag source and provides default implementations of /// GiveFeedback and QueryContinueDrag. This override also handles the data object /// creation, including initialization of the drag image from the speicified Bitmap. /// </summary> /// <param name="control">The drag source Control instance.</param> /// <param name="dragImage">A Bitmap to initialize the drag image from.</param> /// <param name="cursorOffset">The drag image cursor offset.</param> /// <returns>The created data object.</returns> /// <remarks>Callers must call UnregisterDefaultDragSource when the drag and drop /// operation is complete to avoid memory leaks.</remarks> public static IDataObject RegisterDefaultDragSource(Control control, Bitmap dragImage, Point cursorOffset) { IDataObject data = CreateDataObject(dragImage, cursorOffset); RegisterDefaultDragSource(control, data); return(data); }
protected internal override IRepositoryBrowserInfo[] OnDragDrop(DragDropEffects effect, int keyState, IDataObject data) { Debug.Assert(effect == DragDropEffects.Copy, "effect == DragDropEffects.Copy"); object[] files = (object[])data.GetData(DataFormats.FileDrop); if (files == null) { return(null); } // The number of repositories we return may not be the same as the number of files dragged in. // If some of them fail to load (eg. they are not COM type libraries) still return the rest. ArrayList repositories = new ArrayList(); foreach (string file in files) { try { repositories.Add(GetTypeLibraryInfo(file)); } catch (System.Exception) { } } return((IRepositoryBrowserInfo[])repositories.ToArray(typeof(IRepositoryBrowserInfo))); }
/// <summary>Gets the file content for the specified FileDescriptor index.</summary> /// <param name="index">The index of the file content to retrieve.</param> public static MemoryStream GetFileContent(this System.Windows.Forms.IDataObject data, int index) { // As this is indexed, "FileContent" is most likely null, so the COM IDataObject needs to be used var comData = (System.Runtime.InteropServices.ComTypes.IDataObject)data; var formatetc = new FORMATETC() { cfFormat = (short)DataFormats.GetFormat("FileContents").Id, dwAspect = DVASPECT.DVASPECT_CONTENT, lindex = index, ptd = IntPtr.Zero, tymed = TYMED.TYMED_ISTREAM | TYMED.TYMED_HGLOBAL }; var medium = new STGMEDIUM(); comData.GetData(ref formatetc, out medium); switch (medium.tymed) { case TYMED.TYMED_HGLOBAL: return(data.GetFileContentFromHGlobal(medium)); case TYMED.TYMED_ISTREAM: return(data.GetFileContentFromIStream(medium)); default: throw new InvalidOperationException($"Cannot get FileContent for {medium.tymed} TYMED."); } }
private void contextMenuStrip1_ItemClicked(object sender, ToolStripItemClickedEventArgs e) { switch (e.ClickedItem.Name) { case "MenuItemCopy": this.txtSend.Copy(); break; case "MenuItemPaset": { System.Windows.Forms.IDataObject data = Clipboard.GetDataObject(); //从剪贴板中获取数据 if (data.GetDataPresent(typeof(Image))) //判断是否是图片类型 { MessageBox.Show(data.GetType().ToString()); } //this.txtSend.Paste(); } break; case "MenuItemCut": this.txtSend.Cut(); break; case "MenuItemDel": this.txtSend.SelectedText = ""; break; case "MenuItemSelAll": this.Focus(); this.txtSend.SelectAll(); break; } }
/// <summary>Gets the array of FileNames from the FileGroupDescriptors format.</summary> public static string[] GetFileContentNames(this System.Windows.Forms.IDataObject data) { var names = new string[data.GetFileContentCount()]; if (names.Length != 0) { var bytes = data.GetFileGroupDescriptor().ToArray(); IntPtr fgdPtr = IntPtr.Zero; try { fgdPtr = Marshal.AllocHGlobal(bytes.Length); int offset = Marshal.SizeOf(typeof(UInt32)); int size = Marshal.SizeOf(typeof(FILEDESCRIPTORW)); for (int i = 0; i < names.Length; i++) { var fd = (FILEDESCRIPTORW)Marshal.PtrToStructure(fgdPtr + offset + (i * size), typeof(FILEDESCRIPTORW)); names[i] = fd.cFileName; } } finally { if (fgdPtr != IntPtr.Zero) { Marshal.FreeHGlobal(fgdPtr); } } } return(names); }
void pictureBox1_KeyDown(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.Delete) { this.pictureBox1.Image = null; DelImage(); } if (e.Control == true && e.KeyCode == Keys.V) { System.Windows.Forms.IDataObject iData = System.Windows.Forms.Clipboard.GetDataObject(); System.Drawing.Image retImage = null; if (iData != null) { if (iData.GetDataPresent(System.Windows.Forms.DataFormats.Bitmap)) { retImage = (System.Drawing.Image)iData.GetData(System.Windows.Forms.DataFormats.Bitmap); } else if (iData.GetDataPresent(System.Windows.Forms.DataFormats.Dib)) { retImage = (System.Drawing.Image)iData.GetData(System.Windows.Forms.DataFormats.Dib); } } if (retImage != null) { AddImage(retImage); } } }
public string ReadMsword(string filePath) { Microsoft.Office.Interop.Word.Application word = new Microsoft.Office.Interop.Word.Application(); try { object miss = System.Reflection.Missing.Value; object path = filePath; //lbWordDocs.Items.Add(filePath); //rtbox.Text() object readOnly = false; Microsoft.Office.Interop.Word.Document docs = word.Documents.Open(ref path, ref miss, ref readOnly, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss); docs.ActiveWindow.Selection.WholeStory(); docs.ActiveWindow.Selection.Copy(); data = Clipboard.GetDataObject(); //rtbox.Text = (string)(data.GetData(DataFormats.Text)); docs.Close(ref miss, ref miss, ref miss); word.Quit(ref miss, ref miss, ref miss); } catch (Exception ex) { MessageBox.Show(ex.ToString()); } finally { System.Runtime.InteropServices.Marshal.ReleaseComObject(word); } //return (data.GetData(DataFormats.Text).ToString()); return(data.GetData(DataFormats.Text).ToString()); }
/// <summary> /// Performs a default drag and drop operation for the specified drag source. /// </summary> /// <param name="control">The drag source Control.</param> /// <param name="dragImage">The Bitmap to initialize the drag image from.</param> /// <param name="cursorOffset">The drag image cursor offset.</param> /// <param name="allowedEffects">The allowed drop effects.</param> /// <param name="data">The associated data.</param> /// <returns>The accepted drop effects from the completed operation.</returns> public static DragDropEffects DoDragDrop(Control control, Bitmap dragImage, Point cursorOffset, DragDropEffects allowedEffects, params KeyValuePair <string, object>[] data) { IDataObject dataObject = RegisterDefaultDragSource(control, dragImage, cursorOffset); return(DoDragDropInternal(control, dataObject, allowedEffects, data)); }
/// <summary> /// Unsets a drop description flag. /// </summary> /// <param name="dataObject">The associated DataObject.</param> /// <param name="flag">The drop description flag to unset.</param> private static void UnsetDropDescriptionFlag(IDataObject dataObject, DropDescriptionFlags flag) { if (s_dropDescriptions.ContainsKey(dataObject)) { DropDescriptionFlags current = s_dropDescriptions[dataObject]; s_dropDescriptions[dataObject] = (current | flag) ^ flag; } }
/// <summary> /// Checks if the IsDefault drop description flag is set for the associated DataObject. /// </summary> /// <param name="dataObject">The associated DataObject.</param> /// <returns>True if the IsDefault flag is set, otherwise False.</returns> private static bool IsDropDescriptionDefault(IDataObject dataObject) { if (s_dropDescriptions.ContainsKey(dataObject)) { return((s_dropDescriptions[dataObject] & DropDescriptionFlags.IsDefault) == DropDescriptionFlags.IsDefault); } return(false); }
/// <summary> /// Invalidates the drag image. /// </summary> /// <param name="dataObject">The data object for which to invalidate the drag image.</param> /// <remarks>This call tells the drag image manager to reformat the internal /// cached drag image, based on the already set drag image bitmap and current drop /// description.</remarks> public static void InvalidateDragImage(IDataObject dataObject) { if (dataObject.GetDataPresent("DragWindow")) { IntPtr hwnd = GetIntPtrFromData(dataObject.GetData("DragWindow")); PostMessage(hwnd, WM_INVALIDATEDRAGIMAGE, IntPtr.Zero, IntPtr.Zero); } }
int IOleDropTarget.OleDragLeave() { TraceDebug.Trace("OleDragLeave"); this.owner.OnDragLeave(EventArgs.Empty); lastDataObject = null; this.lastEffect = DragDropEffects.None; return(0); }
/// <summary> /// Creates a DataObject with an internal COM callable implementation of IDataObject. /// This override also sets the drag image to a bitmap created from the specified /// Control instance's UI. It also sets a flag on the system IDragSourceHelper2 to /// allow drop descriptions. /// </summary> /// <param name="control">A Control to initialize the drag image from.</param> /// <param name="cursorOffset">The drag image cursor offset.</param> /// <returns>A new instance of System.Windows.Forms.IDataObject.</returns> public static IDataObject CreateDataObject(Control control, Point cursorOffset) { IDataObject data = CreateDataObject(); AllowDropDescription(true); data.SetDragImage(control, cursorOffset); return(data); }
/// <summary> /// Creates a DataObject with an internal COM callable implementation of IDataObject. /// This override also sets the drag image to the specified Bitmap and sets a flag /// on the system IDragSourceHelper2 to allow drop descriptions. /// </summary> /// <param name="dragImage">A Bitmap from which to create the drag image.</param> /// <param name="cursorOffset">The drag image cursor offset.</param> /// <returns>A new instance of System.Windows.Forms.IDataObject.</returns> public static IDataObject CreateDataObject(Bitmap dragImage, Point cursorOffset) { IDataObject data = CreateDataObject(); AllowDropDescription(true); data.SetDragImage(dragImage, cursorOffset); return(data); }
public MyDataObject(System.Windows.Forms.IDataObject underlyingDataObject) { this.underlyingDataObject = underlyingDataObject; this.comUnderlyingDataObject = (System.Runtime.InteropServices.ComTypes.IDataObject) this.underlyingDataObject; //FieldInfo innerDataField = this.underlyingDataObject.GetType().GetField("innerData", BindingFlags.NonPublic | BindingFlags.Instance); //this.oleUnderlyingDataObject = (System.Windows.Forms.IDataObject)innerDataField.GetValue(this.underlyingDataObject); //this.getDataFromHGLOBLALMethod = this.underlyingDataObject.GetType().GetMethod("GetDataFromHGLOBLAL", BindingFlags.NonPublic | BindingFlags.Instance); }
private static MemoryStream GetFileContentFromHGlobal(this System.Windows.Forms.IDataObject data, STGMEDIUM medium) { var innerDataField = data.GetType().GetField("innerData", BindingFlags.NonPublic | BindingFlags.Instance); var oldData = (System.Windows.Forms.IDataObject)innerDataField.GetValue(data); var getDataFromHGLOBLALMethod = oldData.GetType().GetMethod("GetDataFromHGLOBLAL", BindingFlags.NonPublic | BindingFlags.Instance); return((MemoryStream)getDataFromHGLOBLALMethod.Invoke(oldData, new object[] { "FileContents", medium.unionmember })); }
/// <summary> /// Checks if the InvalidateRequired drop description flag is set for the associated DataObject. /// </summary> /// <param name="dataObject">The associated DataObject.</param> /// <returns>True if the InvalidateRequired flag is set, otherwise False.</returns> private static bool InvalidateRequired(IDataObject dataObject) { if (s_dropDescriptions.ContainsKey(dataObject)) { return((s_dropDescriptions[dataObject] & DropDescriptionFlags.InvalidateRequired) == DropDescriptionFlags.InvalidateRequired); } return(false); }
/// <include file='doc\OleDataObject.uex' path='docs/doc[@for=OleDataObject.OleDataObject1]/*' /> public OleDataObject(IDataObject winData) : base(winData) { this.oleData = winData as IOleDataObject; if (null == this.oleData) { oleData = (IOleDataObject)(new Ole2BclDataObject(this as IComDataObject)); } }
/// <summary> /// Extracts data of type <c>Dataformat.Html</c> from an <c>IDataObject</c> data container /// This method shouldn't throw any exception but writes relevant exception informations in the debug window /// </summary> /// <param name="data">data container</param> /// <returns>A byte[] array with the decoded string or null if the method fails</returns> /// <remarks>Added 2006-06-12, <c>Uwe Keim</c>.</remarks> private static byte[] getHtml( IDataObject data) { var interopData = (System.Runtime.InteropServices.ComTypes.IDataObject)data; var format = new FORMATETC { cfFormat = ((short)DataFormats.GetFormat(DataFormats.Html).Id), dwAspect = DVASPECT.DVASPECT_CONTENT, lindex = (-1), tymed = TYMED.TYMED_HGLOBAL }; STGMEDIUM stgmedium; stgmedium.tymed = TYMED.TYMED_HGLOBAL; stgmedium.pUnkForRelease = null; var queryResult = interopData.QueryGetData(ref format); if (queryResult != 0) { return(null); } interopData.GetData(ref format, out stgmedium); if (stgmedium.unionmember == IntPtr.Zero) { return(null); } var pointer = stgmedium.unionmember; var handleRef = new HandleRef(null, pointer); byte[] rawArray; try { var ptr1 = GlobalLock(handleRef); var length = GlobalSize(handleRef); rawArray = new byte[length]; Marshal.Copy(ptr1, rawArray, 0, length); } finally { GlobalUnlock(handleRef); } return(rawArray); }
/// <summary> /// Gets the current DropDescription's drop image type. /// </summary> /// <param name="dataObject">The DataObject.</param> /// <returns>The current drop image type.</returns> private static DropImageType GetDropImageType(IDataObject dataObject) { object data = ((System.Runtime.InteropServices.ComTypes.IDataObject)dataObject).GetDropDescription(); if (data is DropDescription) { return((DropImageType)((DropDescription)data).type); } return(DropImageType.Invalid); }
private static void SetDropTip(IDataObject pdtobj, DROPIMAGETYPE type, string pszMsg, string pszInsert) { var dd = new DROPDESCRIPTION { type = type, szMessage = pszMsg, szInsert = pszInsert }; var hmem = dd.MarshalToPtr(Marshal.AllocHGlobal, out var _); try { SetBlob(pdtobj, (short)RegisterClipboardFormat(ShellClipboardFormat.CFSTR_DROPDESCRIPTION), hmem); } catch { Marshal.FreeHGlobal(hmem); } }
/// <summary> /// Extracts data of type <c>Dataformat.Html</c> from an <c>IDataObject</c> data container /// This method shouldn't throw any exception but writes relevant exception informations in the debug window /// </summary> /// <param name="data">data container</param> /// <returns>A byte[] array with the decoded string or null if the method fails</returns> /// <remarks>Added 2006-06-12, <c>Uwe Keim</c>.</remarks> private static byte[] getHtml( IDataObject data) { var interopData = (System.Runtime.InteropServices.ComTypes.IDataObject)data; var format = new FORMATETC { cfFormat = ((short)DataFormats.GetFormat(DataFormats.Html).Id), dwAspect = DVASPECT.DVASPECT_CONTENT, lindex = (-1), tymed = TYMED.TYMED_HGLOBAL }; STGMEDIUM stgmedium; stgmedium.tymed = TYMED.TYMED_HGLOBAL; stgmedium.pUnkForRelease = null; var queryResult = interopData.QueryGetData(ref format); if (queryResult != 0) { return null; } interopData.GetData(ref format, out stgmedium); if (stgmedium.unionmember == IntPtr.Zero) { return null; } var pointer = stgmedium.unionmember; var handleRef = new HandleRef(null, pointer); byte[] rawArray; try { var ptr1 = GlobalLock(handleRef); var length = GlobalSize(handleRef); rawArray = new byte[length]; Marshal.Copy(ptr1, rawArray, 0, length); } finally { GlobalUnlock(handleRef); } return rawArray; }
/// <summary> /// Initializes a new instance of the <see cref="OutlookDataObject"/> class. /// </summary> /// <param name="underlyingDataObject">The underlying data object to wrap.</param> public OutlookDataObject(System.Windows.Forms.IDataObject underlyingDataObject) { //get the underlying dataobject and its ComType IDataObject interface to it this.underlyingDataObject = underlyingDataObject; this.comUnderlyingDataObject = (System.Runtime.InteropServices.ComTypes.IDataObject)this.underlyingDataObject; //get the internal ole dataobject and its GetDataFromHGLOBLAL so it can be called later FieldInfo innerDataField = this.underlyingDataObject.GetType().GetField("innerData", BindingFlags.NonPublic | BindingFlags.Instance); this.oleUnderlyingDataObject = (System.Windows.Forms.IDataObject)innerDataField.GetValue(this.underlyingDataObject); this.getDataFromHGLOBLALMethod = this.oleUnderlyingDataObject.GetType().GetMethod("GetDataFromHGLOBLAL", BindingFlags.NonPublic | BindingFlags.Instance); }
/// <summary> /// Sets a drop description flag. /// </summary> /// <param name="dataObject">The associated DataObject.</param> /// <param name="flag">The drop description flag to set.</param> private static void SetDropDescriptionFlag(IDataObject dataObject, DropDescriptionFlags flag) { if (s_dropDescriptions.ContainsKey(dataObject)) { s_dropDescriptions[dataObject] |= flag; } else { s_dropDescriptions.Add(dataObject, flag); } }
public ExtendedDragEventHandlerArgs( IDataObject data, int keyState, int x, int y, DragDropEffects allowedEffect, DragDropEffects effect, HtmlDocumentHandle document = default (HtmlDocumentHandle)) : base(data, keyState, x, y, allowedEffect, effect) { Document = document; }
/// <summary> /// Initializes a new instance of the <see cref="DataObject"/> class. /// </summary> /// <param name="underlyingDataObject">The underlying data object to wrap.</param> public DataObject(IDataObject underlyingDataObject) { //get the underlying dataobject and its ComType IDataObject interface to it _underlyingDataObject = underlyingDataObject; _comUnderlyingDataObject = (System.Runtime.InteropServices.ComTypes.IDataObject)_underlyingDataObject; //get the internal ole dataobject and its GetDataFromHGLOBLAL so it can be called later var innerDataField = _underlyingDataObject.GetType().GetField("innerData", BindingFlags.NonPublic | BindingFlags.Instance); // ReSharper disable once PossibleNullReferenceException _oleUnderlyingDataObject = (IDataObject)innerDataField.GetValue(_underlyingDataObject); _getDataFromHgloblalMethod = _oleUnderlyingDataObject.GetType() .GetMethod("GetDataFromHGLOBLAL", BindingFlags.NonPublic | BindingFlags.Instance); }
///<Summary>Constructor starting with a .Net Data object /// .Net DataObjects are easy to work with, but are useless /// if the Dragged items are non-FileSystem /// The DragWrapper class will never call this. /// It is here for playing around with the CDragWrapper class /// </Summary> public CProcDataObject(System.Windows.Forms.DataObject NetObject) { NetIDO = NetObject; ProcessNetDataObject(NetObject); if (m_IsValid) { try { m_DataObject = Marshal.GetComInterfaceForObject(NetObject, Type.GetTypeFromCLSID(new Guid("0000010e-0000-0000-C000-000000000046"), true)); } catch (Exception ex) { Debug.WriteLine("Failed to get COM IDataObject:" + ex.ToString()); m_DataObject = IntPtr.Zero; m_Draglist = new ArrayList(); //let GC clean em up m_IsValid = false; } } }
//Assumed to be a pointer to an IDataObject ///<Summary>This constructor takes a pointer to an IDataObject obtained from a /// IDropTarget Interface's DragEnter method. /// If the pointer points to a .Net DataObject (which only happens within the same app), /// convert it and call ProcessNetDataObject /// Otherwise, it from another app, possibly Win Explorer, so /// check it for the required formats and build m_DragList. /// Any error just quits, leaving m_IsValid as False ... Caller must check ///</Summary> public CProcDataObject(IntPtr pDataObj) { //save it off -- DragWrapper class won't use it // CDragWrapper class may, but should, in this version, use the original m_DataObject = pDataObj; bool HadError = false; //used for various error conditions try { IDO = Marshal.GetTypedObjectForIUnknown(pDataObj, typeof(ShellDll.IDataObject)) as ShellDll.IDataObject; } catch (Exception) { // Debug.WriteLine("Exception Thrown in CMyDataObject -Getting COM interface: " & vbCrLf & ex.ToString) HadError = true; } //If it is really a .Net IDataObject, then treat it as such if (HadError) { try { NetIDO = Marshal.GetTypedObjectForIUnknown(pDataObj, typeof(System.Windows.Forms.IDataObject)) as System.Windows.Forms.IDataObject; IsNet = true; } catch { IsNet = false; } } if (IsNet) { //Any error in ProcessNetDataObject will leave m_IsValid as False -- our only Error Indicator ProcessNetDataObject(NetIDO); } else //IDataObject not from Net, Do it the hard way { if (HadError) { return; //can do no more } ProcessCOMIDataObject(IDO); //It either worked or not. m_IsValid is set accordingly, so we are done } }
/// <summary> /// Performs a default drag and drop operation for the specified drag source. /// </summary> /// <param name="control">The drag source Control.</param> /// <param name="dataObject">The data object associated to the drag and drop operation.</param> /// <param name="allowedEffects">The allowed drop effects.</param> /// <param name="data">The associated data.</param> /// <returns>The accepted drop effects from the completed operation.</returns> private static DragDropEffects DoDragDropInternal(Control control, IDataObject dataObject, DragDropEffects allowedEffects, KeyValuePair<string, object>[] data) { // Set the data onto the data object. if (data != null) { foreach (var dataPair in data) dataObject.SetDataEx(dataPair.Key, dataPair.Value); } try { return control.DoDragDrop(dataObject, allowedEffects); } finally { UnregisterDefaultDragSource(control); } }
public DragSourceEntry(IDataObject data) { this.data = data; }
/// <summary> /// Provides a default GiveFeedback event handler for drag sources. /// </summary> /// <param name="data">The associated data object for the event.</param> /// <param name="e">The event arguments.</param> public static void DefaultGiveFeedback(IDataObject data, GiveFeedbackEventArgs e) { // For drop targets that don't set the drop description, we'll // set a default one. Drop targets that do set drop descriptions // should set an invalid drop description during DragLeave. bool setDefaultDropDesc = false; bool isDefaultDropDesc = IsDropDescriptionDefault(data); DropImageType currentType = DropImageType.Invalid; if (!IsDropDescriptionValid(data) || isDefaultDropDesc) { currentType = GetDropImageType(data); setDefaultDropDesc = true; } if (IsShowingLayered(data)) { // The default drag source implementation uses drop descriptions, // so we won't use default cursors. e.UseDefaultCursors = false; Cursor.Current = Cursors.Arrow; } else e.UseDefaultCursors = true; // We need to invalidate the drag image to refresh the drop description. // This is tricky to implement correctly, but we try to mimic the Windows // Explorer behavior. We internally use a flag to tell us to invalidate // the drag image, so if that is set, we'll invalidate. Otherwise, we // always invalidate if the drop description was set by the drop target, // *or* if the current drop image is not None. So if we set a default // drop description to anything but None, we'll always invalidate. if (InvalidateRequired(data) || !isDefaultDropDesc || currentType != DropImageType.None) { InvalidateDragImage(data); // The invalidate required flag only lasts for one invalidation SetInvalidateRequired(data, false); } // If the drop description is currently invalid, or if it is a default // drop description already, we should check about re-setting it. if (setDefaultDropDesc) { // Only change if the effect changed if ((DropImageType) e.Effect != currentType) { if (e.Effect == DragDropEffects.Copy) data.SetDropDescription(DropImageType.Copy, "Copy", ""); else if (e.Effect == DragDropEffects.Link) data.SetDropDescription(DropImageType.Link, "Link", ""); else if (e.Effect == DragDropEffects.Move) data.SetDropDescription(DropImageType.Move, "Move", ""); else if (e.Effect == DragDropEffects.None) data.SetDropDescription(DropImageType.None, null, null); SetDropDescriptionIsDefault(data, true); // We can't invalidate now, because the drag image manager won't // pick it up... so we set this flag to invalidate on the next // GiveFeedback event. SetInvalidateRequired(data, true); } } }
DragDropEffects IHtmlEditorComponentContext.DoDragDrop(IDataObject dataObject, DragDropEffects allowedEffects) { return _mshtmlEditor.DoDragDrop(dataObject, allowedEffects); }
/// <summary> /// Determines if the IsShowingLayered flag is set on the data object. /// </summary> /// <param name="dataObject">The data object.</param> /// <returns>True if the flag is set, otherwise false.</returns> private static bool IsShowingLayered(IDataObject dataObject) { if (dataObject.GetDataPresent(IsShowingLayeredFormat)) { object data = dataObject.GetData(IsShowingLayeredFormat); if (data != null) return GetBooleanFromData(data); } return false; }
/// <summary> /// Invalidates the drag image. /// </summary> /// <param name="dataObject">The data object for which to invalidate the drag image.</param> /// <remarks>This call tells the drag image manager to reformat the internal /// cached drag image, based on the already set drag image bitmap and current drop /// description.</remarks> public static void InvalidateDragImage(IDataObject dataObject) { if (dataObject.GetDataPresent("DragWindow")) { IntPtr hwnd = GetIntPtrFromData(dataObject.GetData("DragWindow")); PostMessage(hwnd, WM_INVALIDATEDRAGIMAGE, IntPtr.Zero, IntPtr.Zero); } }
/// <summary> /// Checks if the InvalidateRequired drop description flag is set for the associated DataObject. /// </summary> /// <param name="dataObject">The associated DataObject.</param> /// <returns>True if the InvalidateRequired flag is set, otherwise False.</returns> private static bool InvalidateRequired(IDataObject dataObject) { if (s_dropDescriptions.ContainsKey(dataObject)) return (s_dropDescriptions[dataObject] & DropDescriptionFlags.InvalidateRequired) == DropDescriptionFlags.InvalidateRequired; return false; }
/// <summary> /// Checks if the IsDefault drop description flag is set for the associated DataObject. /// </summary> /// <param name="dataObject">The associated DataObject.</param> /// <returns>True if the IsDefault flag is set, otherwise False.</returns> private static bool IsDropDescriptionDefault(IDataObject dataObject) { if (s_dropDescriptions.ContainsKey(dataObject)) return (s_dropDescriptions[dataObject] & DropDescriptionFlags.IsDefault) == DropDescriptionFlags.IsDefault; return false; }
/// <summary> /// Sets the IsDefault drop description flag for the associated DataObject. /// </summary> /// <param name="dataObject">The associdated DataObject.</param> /// <param name="isDefault">True to set the flag, False to unset it.</param> private static void SetDropDescriptionIsDefault(IDataObject dataObject, bool isDefault) { if (isDefault) SetDropDescriptionFlag(dataObject, DropDescriptionFlags.IsDefault); else UnsetDropDescriptionFlag(dataObject, DropDescriptionFlags.IsDefault); }
/// <summary> /// Registers a Control as a drag source and provides default implementations of /// GiveFeedback and QueryContinueDrag. /// </summary> /// <param name="control">The drag source Control instance.</param> /// <param name="data">The DataObject associated to the drag source.</param> /// <remarks>Callers must call UnregisterDefaultDragSource when the drag and drop /// operation is complete to avoid memory leaks.</remarks> public static void RegisterDefaultDragSource(Control control, IDataObject data) { // Cache the drag source and the associated data object var entry = new DragSourceEntry(data); if (!s_dataContext.ContainsKey(control)) s_dataContext.Add(control, entry); else s_dataContext[control] = entry; // We need to listen for drop description changes. If a drop target // changes the drop description, we shouldn't provide a default one. entry.adviseConnection = ((System.Runtime.InteropServices.ComTypes.IDataObject) data).Advise(new AdviseSink(data), DropDescriptionFormat, 0); // Hook up the default drag source event handlers control.GiveFeedback += DefaultGiveFeedbackHandler; control.QueryContinueDrag += DefaultQueryContinueDragHandler; }
/// <summary> /// Sets the InvalidatedRequired drop description flag for the associated DataObject. /// </summary> /// <param name="dataObject">The associdated DataObject.</param> /// <param name="isDefault">True to set the flag, False to unset it.</param> private static void SetInvalidateRequired(IDataObject dataObject, bool required) { if (required) SetDropDescriptionFlag(dataObject, DropDescriptionFlags.InvalidateRequired); else UnsetDropDescriptionFlag(dataObject, DropDescriptionFlags.InvalidateRequired); }
/// <summary> /// Sets a drop description flag. /// </summary> /// <param name="dataObject">The associated DataObject.</param> /// <param name="flag">The drop description flag to set.</param> private static void SetDropDescriptionFlag(IDataObject dataObject, DropDescriptionFlags flag) { if (s_dropDescriptions.ContainsKey(dataObject)) s_dropDescriptions[dataObject] |= flag; else s_dropDescriptions.Add(dataObject, flag); }
/// <summary> /// Unsets a drop description flag. /// </summary> /// <param name="dataObject">The associated DataObject.</param> /// <param name="flag">The drop description flag to unset.</param> private static void UnsetDropDescriptionFlag(IDataObject dataObject, DropDescriptionFlags flag) { if (s_dropDescriptions.ContainsKey(dataObject)) { DropDescriptionFlags current = s_dropDescriptions[dataObject]; s_dropDescriptions[dataObject] = (current | flag) ^ flag; } }
/// <summary> /// Gets the current DropDescription's drop image type. /// </summary> /// <param name="dataObject">The DataObject.</param> /// <returns>The current drop image type.</returns> private static DropImageType GetDropImageType(IDataObject dataObject) { object data = ((System.Runtime.InteropServices.ComTypes.IDataObject) dataObject).GetDropDescription(); if (data is DropDescription) return (DropImageType) ((DropDescription) data).type; return DropImageType.Invalid; }
/// <summary> /// Creates an AdviseSink associated to the specified data object. /// </summary> /// <param name="data">The data object.</param> public AdviseSink(IDataObject data) { this.data = data; }