Exemple #1
0
 // IDataObject methods
 int IDataObject.DAdvise(FORMATETC[] e, uint adv, IAdviseSink sink, out uint cookie) {
   STATDATA sdata = new STATDATA();
   sdata.ADVF = adv;
   sdata.FORMATETC = e[0];
   sdata.pAdvSink = sink;
   cookie = this.map.Add(sdata);
   sdata.dwConnection = cookie;
   return 0;
 }
        int IDataObject.DAdvise(FORMATETC[] e, uint adv, IAdviseSink sink, out uint cookie)
        {
            if (e == null)
            {
                throw new ArgumentNullException("e");
            }

            STATDATA sdata = new STATDATA();

            sdata.ADVF = adv;
            sdata.FORMATETC = e[0];
            sdata.pAdvSink = sink;
            cookie = this.map.Add(sdata);
            sdata.dwConnection = cookie;
            return 0;
        }
Exemple #3
0
        public static int QueryGetData(Microsoft.VisualStudio.OLE.Interop.IDataObject pDataObject, ref FORMATETC fmtetc)
        {
            int returnValue = VSConstants.E_FAIL;

            FORMATETC[] af = new FORMATETC[1];
            af[0] = fmtetc;
            try
            {
                int result = ErrorHandler.ThrowOnFailure(pDataObject.QueryGetData(af));
                if (result == VSConstants.S_OK)
                {
                    fmtetc      = af[0];
                    returnValue = VSConstants.S_OK;
                }
            }
            catch (COMException e)
            {
                // do not display exception. We see this also when trying to ask for a Clipboard operation
                // when the actual change was a drag/drop
                returnValue = e.ErrorCode;
            }

            return(returnValue);
        }
        private IEnumerable <string> GetDataFormatsCore()
        {
            var enumFormat = _wrapped.EnumFormatEtc(DATADIR.DATADIR_GET);

            if (enumFormat != null)
            {
                enumFormat.Reset();
                FORMATETC[] formats = new FORMATETC[1];
                int[]       fetched = { 1 };
                while (fetched[0] > 0)
                {
                    fetched[0] = 0;
                    if (enumFormat.Next(1, formats, fetched) == 0 && fetched[0] > 0)
                    {
                        if (formats[0].ptd != IntPtr.Zero)
                        {
                            Marshal.FreeCoTaskMem(formats[0].ptd);
                        }

                        yield return(ClipboardFormats.GetFormat(formats[0].cfFormat));
                    }
                }
            }
        }
Exemple #5
0
        int IComDataObject.QueryGetData(ref FORMATETC formatetc)
        {
            Debug.WriteLineIf(CompModSwitches.DataObject.TraceVerbose, "QueryGetData");
            if (innerData is OleConverter)
            {
                return(((OleConverter)innerData).OleDataObject.QueryGetData(ref formatetc));
            }
            if (formatetc.dwAspect == DVASPECT.DVASPECT_CONTENT)
            {
                if (GetTymedUseable(formatetc.tymed))
                {
                    if (formatetc.cfFormat == 0)
                    {
                        Debug.WriteLineIf(CompModSwitches.DataObject.TraceVerbose, "QueryGetData::returning S_FALSE because cfFormat == 0");
                        return((int)HRESULT.S_FALSE);
                    }
                    else if (!GetDataPresent(DataFormats.GetFormat(formatetc.cfFormat).Name))
                    {
                        return((int)HRESULT.DV_E_FORMATETC);
                    }
                }
                else
                {
                    return((int)HRESULT.DV_E_TYMED);
                }
            }
            else
            {
                return((int)HRESULT.DV_E_DVASPECT);
            }
#if DEBUG
            int format = unchecked ((ushort)formatetc.cfFormat);
            Debug.WriteLineIf(CompModSwitches.DataObject.TraceVerbose, "QueryGetData::cfFormat " + format.ToString(CultureInfo.InvariantCulture) + " found");
#endif
            return((int)HRESULT.S_OK);
        }
        /// <summary>
        /// Determines if data of the requested format is present.
        /// </summary>
        /// <param name="format">The request data format.</param>
        /// <returns>Returns the status of the request. If the data is present, S_OK is returned.
        /// If the data is not present, an error code with the best guess as to the reason is returned.</returns>
        public int QueryGetData(ref FORMATETC format)
        {
            // We only support CONTENT aspect
            if ((DVASPECT.DVASPECT_CONTENT & format.dwAspect) == 0)
            {
                return(DV_E_DVASPECT);
            }

            int _ret = DV_E_TYMED;

            // Try to locate the data
            // TODO_ The ret, if not S_OK, is only relevant to the last item
            foreach (KeyValuePair <FORMATETC, STGMEDIUM> _pair in m_storage)
            {
                if ((_pair.Key.tymed & format.tymed) > 0)
                {
                    if (_pair.Key.cfFormat == format.cfFormat)
                    {
                        // Found it, return S_OK;
                        return(0);
                    }
                    else
                    {
                        // Found the medium type, but wrong format
                        _ret = DV_E_CLIPFORMAT;
                    }
                }
                else
                {
                    // Mismatch on medium type
                    _ret = DV_E_TYMED;
                }
            }

            return(_ret);
        }
 int IShellExtInit.Initialize(IntPtr pidlFolder, IntPtr lpdobj, uint hKeyProgID)
 {
     try
     {
         _CurrentDataObject = null;
         if (lpdobj != (IntPtr)0)
         {
             _CurrentDataObject = (Win32API.IDataObject)Marshal.GetObjectForIUnknown(lpdobj);
             FORMATETC formatEtc = new FORMATETC();
             formatEtc.cfFormat = 15;
             formatEtc.ptd      = IntPtr.Zero;
             formatEtc.dwAspect = DVASPECT.DVASPECT_CONTENT;
             formatEtc.lindex   = -1;
             formatEtc.tymed    = TYMED.TYMED_HGLOBAL;
             STGMEDIUM stgMedium = new STGMEDIUM();
             _CurrentDataObject.GetData(ref formatEtc, ref stgMedium);
             _UnionMember = stgMedium.unionmember.ToInt32();
         }
     }
     catch (Exception)
     {
     }
     return(S_OK);
 }
Exemple #8
0
        /// <summary>
        /// Returns a dataobject from selected nodes
        /// </summary>
        /// <param name="cutHighlightItems">boolean that defines if the selected items must be cut</param>
        /// <returns>data object for selected items</returns>
        internal virtual DataObject PackageSelectionDataObject(bool cutHighlightItems)
        {
            this.CleanupSelectionDataObject(false, false, false);
            StringBuilder sb = new StringBuilder();

            DataObject dataObject = null;

            try
            {
                IList <HierarchyNode> selectedNodes = this.GetSelectedNodes();
                if (selectedNodes != null)
                {
                    this.InstantiateItemsDraggedOrCutOrCopiedList();

                    StringBuilder selectionContent = null;

                    // If there is a selection package the data
                    if (selectedNodes.Count > 1)
                    {
                        foreach (HierarchyNode node in selectedNodes)
                        {
                            selectionContent = node.PrepareSelectedNodesForClipBoard();
                            if (selectionContent != null)
                            {
                                sb.Append(selectionContent);
                            }
                        }
                    }
                    else if (selectedNodes.Count == 1)
                    {
                        HierarchyNode selectedNode = selectedNodes[0];
                        selectionContent = selectedNode.PrepareSelectedNodesForClipBoard();
                        if (selectionContent != null)
                        {
                            sb.Append(selectionContent);
                        }
                    }
                }

                // Add the project items first.
                IntPtr ptrToItems = this.PackageSelectionData(sb, false);
                if (ptrToItems == IntPtr.Zero)
                {
                    return(null);
                }

                FORMATETC fmt = DragDropHelper.CreateFormatEtc(DragDropHelper.CF_VSSTGPROJECTITEMS);
                dataObject = new DataObject();
                dataObject.SetData(fmt, ptrToItems);

                // Now add the project path that sourced data. We just write the project file path.
                IntPtr ptrToProjectPath = this.PackageSelectionData(new StringBuilder(this.GetMkDocument()), true);

                if (ptrToProjectPath != IntPtr.Zero)
                {
                    dataObject.SetData(DragDropHelper.CreateFormatEtc(DragDropHelper.CF_VSPROJECTCLIPDESCRIPTOR), ptrToProjectPath);
                }

                if (cutHighlightItems)
                {
                    bool first             = true;
                    IVsUIHierarchyWindow w = UIHierarchyUtilities.GetUIHierarchyWindow(this.site, HierarchyNode.SolutionExplorer);

                    foreach (HierarchyNode node in this.ItemsDraggedOrCutOrCopied)
                    {
                        ErrorHandler.ThrowOnFailure(w.ExpandItem((IVsUIHierarchy)this, node.ID, first ? EXPANDFLAGS.EXPF_CutHighlightItem : EXPANDFLAGS.EXPF_AddCutHighlightItem));
                        first = false;
                    }
                }
            }
            catch (COMException e)
            {
                Trace.WriteLine("Exception : " + e.Message);

                dataObject = null;
            }

            return(dataObject);
        }
Exemple #9
0
 public static STGMEDIUM GetData(Microsoft.VisualStudio.OLE.Interop.IDataObject pDataObject, ref FORMATETC fmtetc)
 {
     FORMATETC[] af = new FORMATETC[1];
     af[0] = fmtetc;
     STGMEDIUM[] sm = new STGMEDIUM[1];
     pDataObject.GetData(af, sm);
     fmtetc = af[0];
     return(sm[0]);
 }
Exemple #10
0
 public DataCacheEntry(FORMATETC fmt, IntPtr data, DATADIR dir)
 {
     this.format  = fmt;
     this.data    = (long)data;
     this.dataDir = dir;
 }
 public static int QueryGetData(Microsoft.VisualStudio.OLE.Interop.IDataObject pDataObject, ref FORMATETC fmtetc) {
     FORMATETC[] af = new FORMATETC[1];
     af[0] = fmtetc;
     int result = pDataObject.QueryGetData(af);
     if (result == VSConstants.S_OK) {
         fmtetc = af[0];
         return VSConstants.S_OK;
     }
     return result;
 }
Exemple #12
0
        /// <summary>
        /// Determines if data of the requested format is present.
        /// </summary>
        /// <param name="format">The request data format.</param>
        /// <returns>Returns the status of the request. If the data is present, S_OK is returned.
        /// If the data is not present, an error code with the best guess as to the reason is returned.</returns>
        public int QueryGetData(ref FORMATETC format)
        {
            // We only support CONTENT aspect
            if ((DVASPECT.DVASPECT_CONTENT & format.dwAspect) == 0)
                return DV_E_DVASPECT;

            int ret = DV_E_TYMED;

            // Try to locate the data
            // TODO: The ret, if not S_OK, is only relevant to the last item
            foreach (KeyValuePair<FORMATETC, STGMEDIUM> pair in storage)
            {
                if ((pair.Key.tymed & format.tymed) > 0)
                {
                    if (pair.Key.cfFormat == format.cfFormat)
                    {
                        // Found it, return S_OK;
                        return 0;
                    }
                    else
                    {
                        // Found the medium type, but wrong format
                        ret = DV_E_CLIPFORMAT;
                    }
                }
                else
                {
                    // Mismatch on medium type
                    ret = DV_E_TYMED;
                }
            }

            return ret;
        }
 void IDataObject.GetDataHere(FORMATETC[] fmt, STGMEDIUM[] m) {
 }
Exemple #14
0
 /// <summary>
 /// Creates an instance from an array of FORMATETC's.
 /// </summary>
 /// <param name="formats">Array of formats to enumerate.</param>
 private EnumFORMATETC(FORMATETC[] formats)
 {
     // Get the formats as a copy of the array
     this.formats = new FORMATETC[formats.Length];
     formats.CopyTo(this.formats, 0);
 }
Exemple #15
0
            /// <summary>
            /// Retrieves the next elements from the enumeration.
            /// </summary>
            /// <param name="celt">The number of elements to retrieve.</param>
            /// <param name="rgelt">An array to receive the formats requested.</param>
            /// <param name="pceltFetched">An array to receive the number of element fetched.</param>
            /// <returns>If the fetched number of formats is the same as the requested number, S_OK is returned.
            /// There are several reasons S_FALSE may be returned: (1) The requested number of elements is less than
            /// or equal to zero. (2) The rgelt parameter equals null. (3) There are no more elements to enumerate.
            /// (4) The requested number of elements is greater than one and pceltFetched equals null or does not
            /// have at least one element in it. (5) The number of fetched elements is less than the number of
            /// requested elements.</returns>
            public int Next(int celt, FORMATETC[] rgelt, int[] pceltFetched)
            {
                // Start with zero fetched, in case we return early
                if (pceltFetched != null && pceltFetched.Length > 0)
                    pceltFetched[0] = 0;

                // This will count down as we fetch elements
                int cReturn = celt;

                // Short circuit if they didn't request any elements, or didn't
                // provide room in the return array, or there are not more elements
                // to enumerate.
                if (celt <= 0 || rgelt == null || currentIndex >= formats.Length)
                    return 1; // S_FALSE

                // If the number of requested elements is not one, then we must
                // be able to tell the caller how many elements were fetched.
                if ((pceltFetched == null || pceltFetched.Length < 1) && celt != 1)
                    return 1; // S_FALSE

                // If the number of elements in the return array is too small, we
                // throw. This is not a likely scenario, hence the exception.
                if (rgelt.Length < celt)
                    throw new ArgumentException(
                        "The number of elements in the return array is less than the number of elements requested");

                // Fetch the elements.
                for (int i = 0; currentIndex < formats.Length && cReturn > 0; i++, cReturn--, currentIndex++)
                    rgelt[i] = formats[currentIndex];

                // Return the number of elements fetched
                if (pceltFetched != null && pceltFetched.Length > 0)
                    pceltFetched[0] = celt - cReturn;

                // cReturn has the number of elements requested but not fetched.
                // It will be greater than zero, if multiple elements were requested
                // but we hit the end of the enumeration.
                return (cReturn == 0) ? 0 : 1; // S_OK : S_FALSE
            }
Exemple #16
0
 /// <summary>
 /// Determines if the formats are compatible.
 /// </summary>
 /// <param name="format1">A FORMATETC.</param>
 /// <param name="format2">A FORMATETC.</param>
 /// <returns>True if the formats are compatible, otherwise False.</returns>
 /// <remarks>Compatible formats have the same DVASPECT, same format ID, and share
 /// at least one TYMED.</remarks>
 private bool IsFormatCompatible(ref FORMATETC format1, ref FORMATETC format2)
 {
     return ((format1.tymed & format2.tymed) > 0
             && format1.dwAspect == format2.dwAspect
             && format1.cfFormat == format2.cfFormat);
 }
Exemple #17
0
 public AdviseEntry(ref FORMATETC format, ADVF advf, IAdviseSink sink)
 {
     this.format = format;
     this.advf = advf;
     this.sink = sink;
 }
Exemple #18
0
 /// <summary>
 /// Determines if the formats are compatible.
 /// </summary>
 /// <param name="format1">A FORMATETC.</param>
 /// <param name="format2">A FORMATETC.</param>
 /// <returns>True if the formats are compatible, otherwise False.</returns>
 /// <remarks>Compatible formats have the same DVASPECT, same format ID, and share
 /// at least one TYMED.</remarks>
 private bool IsFormatCompatible(FORMATETC format1, FORMATETC format2)
 {
     return IsFormatCompatible(ref format1, ref format2);
 }
Exemple #19
0
        /// <summary>
        /// Gets a data entry by the specified format.
        /// </summary>
        /// <param name="pFormatetc">The format to locate the data entry for.</param>
        /// <param name="dataEntry">The located data entry.</param>
        /// <returns>True if the data entry was found, otherwise False.</returns>
        private bool GetDataEntry(ref FORMATETC pFormatetc, out KeyValuePair<FORMATETC, STGMEDIUM> dataEntry)
        {
            foreach (KeyValuePair<FORMATETC, STGMEDIUM> entry in storage)
            {
                FORMATETC format = entry.Key;
                if (IsFormatCompatible(ref pFormatetc, ref format))
                {
                    dataEntry = entry;
                    return true;
                }
            }

            // Not found... default allocate the out param
            dataEntry = default(KeyValuePair<FORMATETC, STGMEDIUM>);
            return false;
        }
Exemple #20
0
        /// <summary>
        /// Sets data in the specified format into storage.
        /// </summary>
        /// <param name="formatIn">The format of the data.</param>
        /// <param name="medium">The data.</param>
        /// <param name="release">If true, ownership of the medium's memory will be transferred
        /// to this object. If false, a copy of the medium will be created and maintained, and
        /// the caller is responsible for the memory of the medium it provided.</param>
        public void SetData(ref FORMATETC formatIn, ref STGMEDIUM medium, bool release)
        {
            // If the format exists in our storage, remove it prior to resetting it
            foreach (KeyValuePair<FORMATETC, STGMEDIUM> pair in storage)
            {
                if ((pair.Key.tymed & formatIn.tymed) > 0
                    && pair.Key.dwAspect == formatIn.dwAspect
                    && pair.Key.cfFormat == formatIn.cfFormat)
                {
                    STGMEDIUM releaseMedium = pair.Value;
                    ReleaseStgMedium(ref releaseMedium);
                    storage.Remove(pair);
                    break;
                }
            }

            // If release is true, we'll take ownership of the medium.
            // If not, we'll make a copy of it.
            STGMEDIUM sm = medium;
            if (!release)
                sm = CopyMedium(ref medium);

            // Add it to the internal storage
            KeyValuePair<FORMATETC, STGMEDIUM> addPair = new KeyValuePair<FORMATETC, STGMEDIUM>(formatIn, sm);
            storage.Add(addPair);

            RaiseDataChanged(ref addPair);
        }
Exemple #21
0
 /// <summary>
 /// Determines if the formats are compatible.
 /// </summary>
 /// <param name="format1">A FORMATETC.</param>
 /// <param name="format2">A FORMATETC.</param>
 /// <returns>True if the formats are compatible, otherwise False.</returns>
 /// <remarks>Compatible formats have the same DVASPECT, same format ID, and share
 /// at least one TYMED.</remarks>
 private bool IsFormatCompatible(FORMATETC format1, FORMATETC format2)
 {
     return(IsFormatCompatible(ref format1, ref format2));
 }
		internal static void FillFormatEtc(ref FORMATETC template, ushort clipFormat, ref FORMATETC result)
		{
			if (clipFormat != 0)
			{
				result = template;
				result.cfFormat = clipFormat;
				result.ptd = IntPtr.Zero;
				result.dwAspect = (uint)DVASPECT.DVASPECT_CONTENT;
				result.lindex = -1;
				result.tymed = (uint)TYMED.TYMED_NULL;
			}
		}
Exemple #23
0
 public int GetCanonicalFormatEtc(ref FORMATETC formatIn, out FORMATETC formatOut)
 {
     formatOut = formatIn;
     return(DV_E_FORMATETC);
 }
		internal static void OleCopyFormatEtc(ref FORMATETC src, ref FORMATETC dest)
		{
			dest.cfFormat = src.cfFormat;
			dest.ptd = Marshal.AllocCoTaskMem(Marshal.SizeOf(src.ptd));
			Marshal.StructureToPtr(src.ptd, dest.ptd, false);
			dest.dwAspect = src.dwAspect;
			dest.lindex = src.lindex;
			dest.tymed = src.tymed;
		}
 int IDataObject.GetCanonicalFormatEtc(FORMATETC[] format, FORMATETC[] fmt) {
     throw new System.Runtime.InteropServices.COMException("", DATA_S_SAMEFORMATETC);
 }
        public static STGMEDIUM GetData(Microsoft.VisualStudio.OLE.Interop.IDataObject dataObject, ref FORMATETC fmtetc)
        {
            if (dataObject == null)
                throw new ArgumentNullException("dataObject");

            FORMATETC[] af = new FORMATETC[1];
            af[0] = fmtetc;
            STGMEDIUM[] sm = new STGMEDIUM[1];
            dataObject.GetData(af, sm);
            fmtetc = af[0];
            return sm[0];
        }
 void IDataObject.SetData(FORMATETC[] fmt, STGMEDIUM[] m, int fRelease) {
 }
 int IVsSimpleObjectList2.GetClipboardFormat(uint index, uint grfFlags, FORMATETC[] pFormatetc, STGMEDIUM[] pMedium)
 {
     return VSConstants.E_NOTIMPL;
 }
        int IEnumFORMATETC.Next(uint celt, FORMATETC[] d, uint[] fetched) {
            uint rc = 0;
            //uint size = (fetched != null) ? fetched[0] : 0;
            for (uint i = 0; i < celt; i++) {
                if (e.MoveNext()) {
                    DataCacheEntry entry = (DataCacheEntry)e.Current;

                    rc++;
                    if (d != null && d.Length > i) {
                        d[i] = entry.Format;
                    }
                } else {
                    return VSConstants.S_FALSE;
                }
            }

            if (fetched != null && fetched.Length > 0)
                fetched[0] = rc;
            return VSConstants.S_OK;
        }
        void IDataObject.GetData(FORMATETC[] fmt, STGMEDIUM[] m)
        {
            STGMEDIUM retMedium = new STGMEDIUM();

            if(fmt == null || fmt.Length < 1)
                return;

            SafeGlobalAllocHandle copy = null;
            foreach(DataCacheEntry e in this.entries)
            {
                if(e.Format.cfFormat == fmt[0].cfFormat /*|| fmt[0].cfFormat == InternalNativeMethods.CF_HDROP*/)
                {
                    retMedium.tymed = e.Format.tymed;

                    // Caller must delete the memory.
                    copy = DragDropHelper.CopyHGlobal(e.Data);
                    retMedium.unionmember = copy.DangerousGetHandle();
                    break;
                }
            }

            if (m != null && m.Length > 0)
            {
                m[0] = retMedium;
                if (copy != null)
                    copy.SetHandleAsInvalid();
            }
        }
 private int QueryGetDataUnsafe(ref FORMATETC formatetc)
 {
     return(_innerData.QueryGetData(ref formatetc));
 }
 public void SetData(FORMATETC format, SafeGlobalAllocHandle data)
 {
     this.entries.Add(new DataCacheEntry(format, data, DATADIR.DATADIR_SET));
 }
Exemple #33
0
        public static int QueryGetData(Microsoft.VisualStudio.OLE.Interop.IDataObject pDataObject, ref FORMATETC fmtetc)
        {
            FORMATETC[] af = new FORMATETC[1];
            af[0] = fmtetc;
            int hr = pDataObject.QueryGetData(af);

            fmtetc = af[0];
            return(hr);
        }
Exemple #34
0
 /// <summary>
 /// Asks the given list item to renders a specific clipboard format that it supports.
 /// </summary>
 /// <param name="index"></param>
 /// <param name="grfFlags"></param>
 /// <param name="pFormatetc"></param>
 /// <param name="pMedium"></param>
 /// <returns></returns>
 public int GetClipboardFormat(uint index, uint grfFlags, FORMATETC[] pFormatetc, STGMEDIUM[] pMedium)
 {
     throw new NotImplementedException();
 }
Exemple #35
0
 // Public methods
 public void SetData(FORMATETC format, IntPtr data)
 {
     this.entries.Add(new DataCacheEntry(format, data, DATADIR.DATADIR_SET));
 }
Exemple #36
0
 public int GetDataHere(ref FORMATETC format, ref STGMEDIUM medium)
 {
     log.DebugFormat("IDataObject.QueryGetData called -- cfFormat {0} dwAspect {1} lindex {2} ptd {3} tymed {4}", format.cfFormat, format.dwAspect, format.lindex, format.ptd, format.tymed);
     return(NativeMethods.E_NOTIMPL);
 }
Exemple #37
0
 /// <summary>
 /// Gets the specified data.
 /// </summary>
 /// <param name="format">The requested data format.</param>
 /// <param name="medium">When the function returns, contains the requested data.</param>
 public void GetData(ref FORMATETC format, out STGMEDIUM medium)
 {
     medium = new STGMEDIUM();
     GetDataHere(ref format, ref medium);
 }
Exemple #38
0
 public int DAdvise(ref FORMATETC pFormatetc, ADVF advf, IAdviseSink adviseSink, out int connection)
 {
     return(innerData.DAdvise(pFormatetc, advf, adviseSink, out connection));
 }
Exemple #39
0
 /// <summary>
 /// Determines if the formats are compatible.
 /// </summary>
 /// <param name="format1">A FORMATETC.</param>
 /// <param name="format2">A FORMATETC.</param>
 /// <returns>True if the formats are compatible, otherwise False.</returns>
 /// <remarks>Compatible formats have the same DVASPECT, same format ID, and share
 /// at least one TYMED.</remarks>
 private bool IsFormatCompatible(ref FORMATETC format1, ref FORMATETC format2)
 {
     return((format1.tymed & format2.tymed) > 0 && format1.dwAspect == format2.dwAspect && format1.cfFormat == format2.cfFormat);
 }
Exemple #40
0
        /// <summary>
        /// Retrieves the data associated with the specified data format at the specified index.
        /// </summary>
        /// <param name="Format">The format of the data to retrieve. See <see cref="T:System.Windows.DataFormats"></see> for predefined formats.</param>
        /// <param name="Index">The index of the data to retrieve.</param>
        /// <returns>
        /// A <see cref="MemoryStream"/> containing the raw data for the specified data format at the specified index.
        /// </returns>
        private MemoryStream GetContentData(string Format, int Index)
        {
            //create a FORMATETC struct to request the data with
            FORMATETC Formatetc = new FORMATETC
            {
                cfFormat = (short)DataFormats.GetFormat(Format).Id,
                dwAspect = DVASPECT.DVASPECT_CONTENT,
                lindex   = Index,
                ptd      = new IntPtr(0),
                tymed    = TYMED.TYMED_ISTREAM | TYMED.TYMED_ISTORAGE | TYMED.TYMED_HGLOBAL
            };

            //using the Com IDataObject interface get the data using the defined FORMATETC
            comUnderlyingDataObject.GetData(ref Formatetc, out STGMEDIUM Medium);

            //retrieve the data depending on the returned store type
            switch (Medium.tymed)
            {
            case TYMED.TYMED_ISTORAGE:
            {
                //to handle a IStorage it needs to be written into a second unmanaged
                //memory mapped storage and then the data can be read from memory into
                //a managed byte and returned as a MemoryStream

                try
                {
                    //marshal the returned pointer to a IStorage object
                    Ole32.IStorage IStorageObject = (Ole32.IStorage)Marshal.GetObjectForIUnknown(Medium.unionmember);

                    try
                    {
                        //create a ILockBytes (unmanaged byte array) and then create a IStorage using the byte array as a backing store
                        Ole32.CreateILockBytesOnHGlobal(IntPtr.Zero, true, out Ole32.ILockBytes LockBytes);
                        Ole32.StgCreateDocfileOnILockBytes(LockBytes, STGM.STGM_READWRITE | STGM.STGM_SHARE_EXCLUSIVE | STGM.STGM_CREATE, ppstgOpen: out Ole32.IStorage IStorageObjectCopy);

                        try
                        {
                            //copy the returned IStorage into the new IStorage
                            IStorageObject.CopyTo(snbExclude: IntPtr.Zero, pstgDest: IStorageObjectCopy);
                            LockBytes.Flush();
                            IStorageObjectCopy.Commit(Ole32.STGC.STGC_DEFAULT);

                            //get the STATSTG of the LockBytes to determine how many bytes were written to it
                            LockBytes.Stat(out STATSTG LockBytesStat, Ole32.STATFLAG.STATFLAG_NONAME);

                            int CbSize = Convert.ToInt32(LockBytesStat.cbSize);

                            IntPtr LockBytesContentPtr = Marshal.AllocHGlobal(CbSize);

                            try
                            {
                                LockBytes.ReadAt(0, LockBytesContentPtr, Convert.ToUInt32(LockBytesStat.cbSize), out _);

                                byte[] LockBytesContent = new byte[CbSize];

                                Marshal.Copy(LockBytesContentPtr, LockBytesContent, 0, LockBytesContent.Length);

                                return(new MemoryStream(LockBytesContent));
                            }
                            finally
                            {
                                Marshal.FreeHGlobal(LockBytesContentPtr);
                            }
                        }
                        finally
                        {
                            Marshal.ReleaseComObject(IStorageObjectCopy);
                            Marshal.ReleaseComObject(LockBytes);
                        }
                    }
                    finally
                    {
                        Marshal.ReleaseComObject(IStorageObject);
                    }
                }
                finally
                {
                    Marshal.Release(Medium.unionmember);
                }
            }

            case TYMED.TYMED_ISTREAM:
            {
                //to handle a IStream it needs to be read into a managed byte and
                //returned as a MemoryStream

                IStream IStreamObject = (IStream)Marshal.GetObjectForIUnknown(Medium.unionmember);

                try
                {
                    //get the STATSTG of the IStream to determine how many bytes are in it
                    IStreamObject.Stat(out STATSTG iStreamStat, 0);

                    byte[] IStreamContent = new byte[(Convert.ToInt32(iStreamStat.cbSize))];

                    IStreamObject.Read(IStreamContent, IStreamContent.Length, IntPtr.Zero);

                    return(new MemoryStream(IStreamContent));
                }
                finally
                {
                    Marshal.Release(Medium.unionmember);
                    Marshal.ReleaseComObject(IStreamObject);
                }
            }

            case TYMED.TYMED_HGLOBAL:
            {
                //to handle a HGlobal the exisitng "GetDataFromHGLOBAL" method is invoked via
                //reflection

                try
                {
                    return((MemoryStream)getDataFromHGLOBALMethod.Invoke(oleUnderlyingDataObject, new object[] { DataFormats.GetFormat(Formatetc.cfFormat).Name, Medium.unionmember }));
                }
                finally
                {
                    Marshal.Release(Medium.unionmember);
                }
            }

            default:
            {
                return(null);
            }
            }
        }
Exemple #41
0
 public AdviseEntry(ref FORMATETC format, ADVF advf, IAdviseSink sink)
 {
     this.format = format;
     this.advf   = advf;
     this.sink   = sink;
 }
Exemple #42
0
        /// <summary>
        /// Gets the specified data.
        /// </summary>
        /// <param name="format">The requested data format.</param>
        /// <param name="medium">When the function returns, contains the requested data.</param>
        /// <remarks>Differs from GetData only in that the STGMEDIUM storage is
        /// allocated and owned by the caller.</remarks>
        public void GetDataHere(ref FORMATETC format, ref STGMEDIUM medium)
        {
            // Locate the data
            KeyValuePair<FORMATETC, STGMEDIUM> dataEntry;
            if (GetDataEntry(ref format, out dataEntry))
            {
                STGMEDIUM source = dataEntry.Value;
                medium = CopyMedium(ref source);
                return;
            }

            // Didn't find it. Return an empty data medium.
            medium = default(STGMEDIUM);
        }
Exemple #43
0
        /// <summary>
        /// Retrieves the data associated with the specified data format at the specified index.
        /// </summary>
        /// <param name="format">The format of the data to retrieve. See <see cref="T:System.Windows.Forms.DataFormats"></see> for predefined formats.</param>
        /// <param name="index">The index of the data to retrieve.</param>
        /// <returns>
        /// A <see cref="MemoryStream"/> containing the raw data for the specified data format at the specified index.
        /// </returns>
        public MemoryStream GetData(string format, int index)
        {
            //create a FORMATETC struct to request the data with
            FORMATETC formatetc = new FORMATETC();

            formatetc.cfFormat = (short)DataFormats.GetDataFormat(format).Id;
            formatetc.dwAspect = DVASPECT.DVASPECT_CONTENT;
            formatetc.lindex   = index;
            formatetc.ptd      = new IntPtr(0);
            formatetc.tymed    = TYMED.TYMED_ISTREAM | TYMED.TYMED_ISTORAGE | TYMED.TYMED_HGLOBAL;

            //create STGMEDIUM to output request results into
            STGMEDIUM medium = new STGMEDIUM();

            //using the Com IDataObject interface get the data using the defined FORMATETC
            this.comUnderlyingDataObject.GetData(ref formatetc, out medium);

            //retrieve the data depending on the returned store type
            switch (medium.tymed)
            {
            case TYMED.TYMED_ISTORAGE:
                //to handle a IStorage it needs to be written into a second unmanaged
                //memory mapped storage and then the data can be read from memory into
                //a managed byte and returned as a MemoryStream

                NativeMethods.IStorage   iStorage   = null;
                NativeMethods.IStorage   iStorage2  = null;
                NativeMethods.ILockBytes iLockBytes = null;
                System.Runtime.InteropServices.ComTypes.STATSTG iLockBytesStat;
                try
                {
                    //marshal the returned pointer to a IStorage object
                    iStorage = (NativeMethods.IStorage)Marshal.GetObjectForIUnknown(medium.unionmember);
                    Marshal.Release(medium.unionmember);

                    //create a ILockBytes (unmanaged byte array) and then create a IStorage using the byte array as a backing store
                    iLockBytes = NativeMethods.CreateILockBytesOnHGlobal(IntPtr.Zero, true);
                    iStorage2  = NativeMethods.StgCreateDocfileOnILockBytes(iLockBytes, 0x00001012, 0);

                    //copy the returned IStorage into the new IStorage
                    iStorage.CopyTo(0, null, IntPtr.Zero, iStorage2);
                    iLockBytes.Flush();
                    iStorage2.Commit(0);

                    //get the STATSTG of the ILockBytes to determine how many bytes were written to it
                    iLockBytesStat = new System.Runtime.InteropServices.ComTypes.STATSTG();
                    iLockBytes.Stat(out iLockBytesStat, 1);
                    int iLockBytesSize = (int)iLockBytesStat.cbSize;

                    //read the data from the ILockBytes (unmanaged byte array) into a managed byte array
                    byte[] iLockBytesContent = new byte[iLockBytesSize];
                    iLockBytes.ReadAt(0, iLockBytesContent, iLockBytesContent.Length, null);

                    //wrapped the managed byte array into a memory stream and return it
                    return(new MemoryStream(iLockBytesContent));
                }
                finally
                {
                    //release all unmanaged objects
                    Marshal.ReleaseComObject(iStorage2);
                    Marshal.ReleaseComObject(iLockBytes);
                    Marshal.ReleaseComObject(iStorage);
                }

            case TYMED.TYMED_ISTREAM:
                //to handle a IStream it needs to be read into a managed byte and
                //returned as a MemoryStream

                IStream iStream = null;
                System.Runtime.InteropServices.ComTypes.STATSTG iStreamStat;
                try
                {
                    //marshal the returned pointer to a IStream object
                    iStream = (IStream)Marshal.GetObjectForIUnknown(medium.unionmember);
                    Marshal.Release(medium.unionmember);

                    //get the STATSTG of the IStream to determine how many bytes are in it
                    iStreamStat = new System.Runtime.InteropServices.ComTypes.STATSTG();
                    iStream.Stat(out iStreamStat, 0);
                    int iStreamSize = (int)iStreamStat.cbSize;

                    //read the data from the IStream into a managed byte array
                    byte[] iStreamContent = new byte[iStreamSize];
                    iStream.Read(iStreamContent, iStreamContent.Length, IntPtr.Zero);

                    //wrapped the managed byte array into a memory stream and return it
                    return(new MemoryStream(iStreamContent));
                }
                finally
                {
                    //release all unmanaged objects
                    Marshal.ReleaseComObject(iStream);
                }

            case TYMED.TYMED_HGLOBAL:
                //to handle a HGlobal the exisitng "GetDataFromHGLOBLAL" method is invoked via
                //reflection

                return((MemoryStream)this.getDataFromHGLOBLALMethod.Invoke(this.oleUnderlyingDataObject, new object[] { DataFormats.GetDataFormat((short)formatetc.cfFormat).Name, medium.unionmember }));
            }

            return(null);
        }
Exemple #44
0
 public void GetDataHere(ref FORMATETC format, ref STGMEDIUM medium)
 {
     throw new NotImplementedException();
 }
Exemple #45
0
        public int EnumFormatEtc(DATADIR direction, out IEnumFORMATETC ppenumFormatEtc)
        {
            IEnumFORMATETC origEnum = null;

            try
            {
                log.DebugFormat("IDataObject.EnumFormatEtc called -- direction {0}", direction);
                switch (direction)
                {
                case DATADIR.DATADIR_GET:
                    //Get original enumerator
                    int result = innerData.EnumFormatEtc(direction, out origEnum);
                    if (result != NativeMethods.S_OK)
                    {
                        ppenumFormatEtc = null;
                        return(result);
                    }

                    //Enumerate original formats
                    List <FORMATETC> formats = new List <FORMATETC>();
                    FORMATETC[]      buffer  = new FORMATETC[] { new FORMATETC() };
                    while (origEnum.Next(1, buffer, null) == NativeMethods.S_OK)
                    {
                        //Convert format from short to unsigned short
                        ushort cfFormat = (ushort)buffer[0].cfFormat;

                        //Do not return text formats -- some applications try to get text before files
                        if (cfFormat != NativeMethods.CF_TEXT && cfFormat != NativeMethods.CF_UNICODETEXT && cfFormat != (ushort)DataObjectHelper.GetClipboardFormat("Csv"))
                        {
                            formats.Add(buffer[0]);
                        }
                    }

                    //Add CF_HDROP format
                    FORMATETC format = new FORMATETC();
                    format.cfFormat = NativeMethods.CF_HDROP;
                    format.dwAspect = DVASPECT.DVASPECT_CONTENT;
                    format.lindex   = -1;
                    format.ptd      = IntPtr.Zero;
                    format.tymed    = TYMED.TYMED_HGLOBAL;
                    formats.Add(format);

                    //Return new enumerator for available formats
                    ppenumFormatEtc = new FormatEtcEnumerator(formats.ToArray());
                    return(NativeMethods.S_OK);

                case DATADIR.DATADIR_SET:
                    //Return original enumerator
                    return(innerData.EnumFormatEtc(direction, out ppenumFormatEtc));

                default:
                    //Invalid direction
                    ppenumFormatEtc = null;
                    return(NativeMethods.E_INVALIDARG);
                }
            }
            catch (Exception ex)
            {
                log.Error("Exception in IDataObject.EnumFormatEtc", ex);
                ppenumFormatEtc = null;
                return(NativeMethods.E_UNEXPECTED);
            }
            finally
            {
                //Release all unmanaged objects
                if (origEnum != null)
                {
                    Marshal.ReleaseComObject(origEnum);
                }
            }
        }
Exemple #46
0
 public int GetCanonicalFormatEtc(ref FORMATETC formatIn, out FORMATETC formatOut)
 {
     throw new NotImplementedException();
 }
Exemple #47
0
        public static int QueryGetData(Microsoft.VisualStudio.OLE.Interop.IDataObject pDataObject, ref FORMATETC fmtetc)
        {
            int returnValue = VSConstants.E_FAIL;
            FORMATETC[] af = new FORMATETC[1];
            af[0] = fmtetc;
            try
            {
                int result = ErrorHandler.ThrowOnFailure(pDataObject.QueryGetData(af));
                if (result == VSConstants.S_OK)
                {
                    fmtetc = af[0];
                    returnValue = VSConstants.S_OK;
                }
            }
            catch (COMException e)
            {
                Trace.WriteLine("COMException : " + e.Message);
                returnValue = e.ErrorCode;
            }

            return returnValue;
        }
Exemple #48
0
 public void SetData(ref FORMATETC formatIn, ref STGMEDIUM medium, bool release)
 {
     throw new NotImplementedException();
 }
 internal void SetData(FORMATETC format, IntPtr data) {
     this.entries.Add(new DataCacheEntry(format, data, DATADIR.DATADIR_SET));
 }
Exemple #50
0
 public int DAdvise(ref FORMATETC pFormatetc, ADVF advf, IAdviseSink adviseSink, out int connection)
 {
     throw new NotImplementedException();
 }
        void IDataObject.GetData(FORMATETC[] fmt, STGMEDIUM[] m) {
            STGMEDIUM retMedium = new STGMEDIUM();

            if (fmt == null || fmt.Length < 1)
                return;

            foreach (DataCacheEntry e in this.entries) {
                if (e.Format.cfFormat == fmt[0].cfFormat /*|| fmt[0].cfFormat == InternalNativeMethods.CF_HDROP*/) {
                    retMedium.tymed = e.Format.tymed;

                    // Caller must delete the memory.
                    retMedium.unionmember = DragDropHelper.CopyHGlobal(new IntPtr(e.Data));
                    break;
                }
            }

            if (m != null && m.Length > 0)
                m[0] = retMedium;
        }
 /// <summary>
 /// Provides data to the client as it becomes available during asynchronous bind operations.
 /// </summary>
 void IBindStatusCallback.OnDataAvailable(BSCF grfBSCF, uint dwSize, ref FORMATETC pformatetc, ref STGMEDIUM pstgmed)
 {
     // never called by URLDownloadToFile
     LOG_UN("IBindStatusCallback", "OnDataAvailable");
 }
        int IDataObject.QueryGetData(FORMATETC[] fmt) {
            if (fmt == null || fmt.Length < 1)
                return VSConstants.S_FALSE;

            foreach (DataCacheEntry e in this.entries) {
                if (e.Format.cfFormat == fmt[0].cfFormat /*|| fmt[0].cfFormat == InternalNativeMethods.CF_HDROP*/)
                    return VSConstants.S_OK;
            }

            return VSConstants.S_FALSE;
        }
Exemple #54
0
        public static int QueryGetData(Microsoft.VisualStudio.OLE.Interop.IDataObject pDataObject, ref FORMATETC fmtetc)
        {
            int returnValue = VSConstants.E_FAIL;

            FORMATETC[] af = new FORMATETC[1];
            af[0] = fmtetc;
            try
            {
                int result = ErrorHandler.ThrowOnFailure(pDataObject.QueryGetData(af));
                if (result == VSConstants.S_OK)
                {
                    fmtetc      = af[0];
                    returnValue = VSConstants.S_OK;
                }
            }
            catch (COMException e)
            {
                Trace.WriteLine("COMException : " + e.Message);
                returnValue = e.ErrorCode;
            }

            return(returnValue);
        }
 public static FORMATETC CreateFormatEtc(ushort iFormat) {
     FORMATETC fmt = new FORMATETC();
     fmt.cfFormat = iFormat;
     fmt.ptd = IntPtr.Zero;
     fmt.dwAspect = (uint)DVASPECT.DVASPECT_CONTENT;
     fmt.lindex = -1;
     fmt.tymed = (uint)TYMED.TYMED_HGLOBAL;
     return fmt;
 }
Exemple #56
0
 internal static void FillFormatEtc(ref FORMATETC template, ushort clipFormat, ref FORMATETC result)
 {
     if (clipFormat != 0)
     {
         result          = template;
         result.cfFormat = clipFormat;
         result.ptd      = IntPtr.Zero;
         result.dwAspect = (uint)DVASPECT.DVASPECT_CONTENT;
         result.lindex   = -1;
         result.tymed    = (uint)TYMED.TYMED_NULL;
     }
 }
 public static STGMEDIUM GetData(Microsoft.VisualStudio.OLE.Interop.IDataObject pDataObject, ref FORMATETC fmtetc) {
     FORMATETC[] af = new FORMATETC[1];
     af[0] = fmtetc;
     STGMEDIUM[] sm = new STGMEDIUM[1];
     pDataObject.GetData(af, sm);
     fmtetc = af[0];
     return sm[0];
 }
            /// <summary>
            ///  Retrieves the specified format data from the bound IComDataObject, from
            ///  other sources that IStream and HGLOBAL... this is really just a place
            ///  to put the "special" formats like BITMAP, ENHMF, etc.
            /// </summary>
            private object?GetDataFromOleOther(string format)
            {
                Debug.Assert(_innerData is not null, "You must have an innerData on all DataObjects");

                FORMATETC formatetc = new FORMATETC();
                STGMEDIUM medium    = new STGMEDIUM();

                TYMED tymed = (TYMED)0;

                if (format.Equals(DataFormats.Bitmap))
                {
                    tymed = TYMED.TYMED_GDI;
                }

                if (tymed == (TYMED)0)
                {
                    return(null);
                }

                formatetc.cfFormat = unchecked ((short)(ushort)(DataFormats.GetFormat(format).Id));
                formatetc.dwAspect = DVASPECT.DVASPECT_CONTENT;
                formatetc.lindex   = -1;
                formatetc.tymed    = tymed;

                object?data = null;

                if ((int)HRESULT.S_OK == QueryGetDataUnsafe(ref formatetc))
                {
                    try
                    {
                        _innerData.GetData(ref formatetc, out medium);
                    }
                    catch
                    {
                    }
                }

                try
                {
                    if (medium.tymed == TYMED.TYMED_GDI && medium.unionmember != IntPtr.Zero)
                    {
                        if (format.Equals(DataFormats.Bitmap))
                        {
                            // ASURT 140870 -- GDI+ doesn't own this HBITMAP, but we can't
                            // delete it while the object is still around.  So we have to do the really expensive
                            // thing of cloning the image so we can release the HBITMAP.

                            // This bitmap is created by the com object which originally copied the bitmap to the
                            // clipboard. We call Add here, since DeleteObject calls Remove.
                            Image clipboardImage = Image.FromHbitmap(medium.unionmember);
                            if (clipboardImage is not null)
                            {
                                Image firstImage = clipboardImage;
                                clipboardImage = (Image)clipboardImage.Clone();
                                firstImage.Dispose();
                            }

                            data = clipboardImage;
                        }
                    }
                }
                finally
                {
                    Ole32.ReleaseStgMedium(ref medium);
                }

                return(data);
            }
 /// <summary>
 /// The IntPtr is data allocated that should be removed. It is allocated by the ProcessSelectionData method.
 /// </summary>
 internal DataCacheEntry(FORMATETC fmt, IntPtr data, DATADIR dir) {
     this.format = fmt;
     this.data = (long)data;
     this.dataDir = dir;
 }
            /// <summary>
            ///  Uses IStream and retrieves the specified format from the bound IComDataObject.
            /// </summary>
            private unsafe object?GetDataFromOleIStream(string format)
            {
                FORMATETC formatetc = new FORMATETC();
                STGMEDIUM medium    = new STGMEDIUM();

                formatetc.cfFormat = unchecked ((short)(ushort)(DataFormats.GetFormat(format).Id));
                formatetc.dwAspect = DVASPECT.DVASPECT_CONTENT;
                formatetc.lindex   = -1;
                formatetc.tymed    = TYMED.TYMED_ISTREAM;

                // Limit the # of exceptions we may throw below.
                if ((int)HRESULT.S_OK != QueryGetDataUnsafe(ref formatetc))
                {
                    return(null);
                }

                try
                {
                    _innerData.GetData(ref formatetc, out medium);
                }
                catch
                {
                    return(null);
                }

                Ole32.IStream?pStream = null;
                IntPtr        hglobal = IntPtr.Zero;

                try
                {
                    if (medium.tymed == TYMED.TYMED_ISTREAM && medium.unionmember != IntPtr.Zero)
                    {
                        pStream = (Ole32.IStream)Marshal.GetObjectForIUnknown(medium.unionmember);
                        pStream.Stat(out Ole32.STATSTG sstg, Ole32.STATFLAG.DEFAULT);

                        hglobal = Kernel32.GlobalAlloc(
                            Kernel32.GMEM.MOVEABLE | Kernel32.GMEM.DDESHARE | Kernel32.GMEM.ZEROINIT,
                            (uint)sstg.cbSize);
                        // not throwing here because the other out of memory condition on GlobalAlloc
                        // happens inside innerData.GetData and gets turned into a null return value
                        if (hglobal == IntPtr.Zero)
                        {
                            return(null);
                        }
                        IntPtr ptr = Kernel32.GlobalLock(hglobal);
                        pStream.Read((byte *)ptr, (uint)sstg.cbSize, null);
                        Kernel32.GlobalUnlock(hglobal);

                        return(GetDataFromHGLOBAL(format, hglobal));
                    }

                    return(null);
                }
                finally
                {
                    if (hglobal != IntPtr.Zero)
                    {
                        Kernel32.GlobalFree(hglobal);
                    }

                    if (pStream is not null)
                    {
                        Marshal.ReleaseComObject(pStream);
                    }

                    Ole32.ReleaseStgMedium(ref medium);
                }
            }