Exemple #1
0
        //
        //////////////////////////////////////////////////////////////

        //////////////////////////////////////////////////////////////
        // OnDataChange
        //
        void IOleAdviseSink.OnDataChange(OleInterop.FORMATETC[] pFormatetc, OleInterop.STGMEDIUM[] pStgmed)
        {
            if (null != oleSink)
            {
                oleSink.OnDataChange(pFormatetc, pStgmed);
            }
            else
            {
                // In order to call the version of this interface defined in the BCL
                // each array must contain exactly one object.
                if ((null == pFormatetc) || (null == pStgmed))
                {
                    throw new ArgumentNullException("");
                }
                if ((1 != pFormatetc.Length) || (1 != pStgmed.Length))
                {
                    throw new InvalidOperationException();
                }

                // Convert the parameters
                BclComTypes.FORMATETC bclFormat = StructConverter.OleFormatETC2Bcl(ref pFormatetc[0]);
                BclComTypes.STGMEDIUM bclMedium = StructConverter.OleSTGMEDIUM2Bcl(ref pStgmed[0]);

                // Now we can call the method on the BCL interface
                bclSink.OnDataChange(ref bclFormat, ref bclMedium);

                // Now we have to copy the parameters back into the original structures.
                pFormatetc[0] = StructConverter.BclFormatETC2Ole(ref bclFormat);
                pStgmed[0]    = StructConverter.BclSTGMEDIUM2Ole(ref bclMedium);
            }
        }
Exemple #2
0
 /// <summary>
 /// Handles DataChanged events from a COM IDataObject.
 /// </summary>
 /// <param name="format">The data format that had a change.</param>
 /// <param name="stgmedium">The data value.</param>
 public void OnDataChange(ref ComTypes.FORMATETC format, ref ComTypes.STGMEDIUM stgmedium)
 {
     // We listen to DropDescription changes, so that we can unset the IsDefault
     // drop description flag.
     object odd = ComTypes.ComDataObjectExtensions.GetDropDescription((ComTypes.IDataObject)data);
     //if (odd != null)
     //DragSourceHelper.SetDropDescriptionIsDefault(data, false);
 }
Exemple #3
0
        //                                                                       FORMATETC
        ///////////////////////////////////////////////////////////////////////////////////

        ///////////////////////////////////////////////////////////////////////////////////
        // STGMEDIUM
        static internal OleInterop.STGMEDIUM BclSTGMEDIUM2Ole(ref BclComTypes.STGMEDIUM bclMedium)
        {
            OleInterop.STGMEDIUM oleMedium;
            oleMedium.pUnkForRelease = bclMedium.pUnkForRelease;
            oleMedium.tymed          = (uint)bclMedium.tymed;
            oleMedium.unionmember    = bclMedium.unionmember;
            return(oleMedium);
        }
        /// <summary>
        /// Gets the file list.
        /// </summary>
        /// <param name="this">The IDataObject instance.</param>
        /// <returns>The file list in the data object.</returns>
        public static List<string> GetFileList(this IDataObject @this)
        {
            //  Create the format object.
            var formatEtc = new FORMATETC();

            //  Set up the format object, based on CF_HDROP.
            formatEtc.cfFormat = (short)CLIPFORMAT.CF_HDROP;
            formatEtc.ptd = IntPtr.Zero;
            formatEtc.dwAspect = DVASPECT.DVASPECT_CONTENT;
            formatEtc.lindex = -1;
            formatEtc.tymed = TYMED.TYMED_HGLOBAL;

            //  Get the data.
            // ReSharper disable RedundantAssignment
            var storageMedium = new STGMEDIUM();
            // ReSharper restore RedundantAssignment
            @this.GetData(ref formatEtc, out storageMedium);

            var fileList = new List<string>();

            //  Things can get risky now.
            try
            {
                //  Get the handle to the HDROP.
                var hDrop = storageMedium.unionmember;
                if (hDrop == IntPtr.Zero)
                    throw new ArgumentException("Failed to get the handle to the drop data.");

                //  Get the count of the files in the operation.
                var fileCount = Shell32.DragQueryFile(hDrop, UInt32.MaxValue, null, 0);

                //  Go through each file.
                for (uint i = 0; i < fileCount; i++)
                {
                    //  Storage for the file name.
                    var fileNameBuilder = new StringBuilder(MaxPath);

                    //  Get the file name.
                    var result = Shell32.DragQueryFile(hDrop, i, fileNameBuilder, (uint)fileNameBuilder.Capacity);

                    //  If we have a valid result, add the file name to the list of files.
                    if (result != 0)
                        fileList.Add(fileNameBuilder.ToString());
                }

            }
            finally
            {
                Ole32.ReleaseStgMedium(ref storageMedium);
            }

            return fileList;
        }
Exemple #5
0
        void BclComTypes.IDataObject.GetData(ref BclComTypes.FORMATETC format, out BclComTypes.STGMEDIUM medium)
        {
            if (null != bclData)
            {
                bclData.GetData(ref format, out medium);
                return;
            }

            OleInterop.FORMATETC[] oleFormat = new OleInterop.FORMATETC[1];
            oleFormat[0] = StructConverter.BclFormatETC2Ole(ref format);
            OleInterop.STGMEDIUM[] oleMedium = new OleInterop.STGMEDIUM[1];
            oleData.GetData(oleFormat, oleMedium);
            medium = StructConverter.OleSTGMEDIUM2Bcl(ref oleMedium[0]);
        }
Exemple #6
0
        void BclComTypes.IDataObject.SetData(ref BclComTypes.FORMATETC formatIn, ref BclComTypes.STGMEDIUM medium, bool release)
        {
            if (null != bclData)
            {
                bclData.SetData(ref formatIn, ref medium, release);
                return;
            }

            OleInterop.FORMATETC[] oleFormat = new OleInterop.FORMATETC[1];
            oleFormat[0] = StructConverter.BclFormatETC2Ole(ref formatIn);
            OleInterop.STGMEDIUM[] oleMedium = new OleInterop.STGMEDIUM[1];
            oleMedium[0] = StructConverter.BclSTGMEDIUM2Ole(ref medium);
            oleData.SetData(oleFormat, oleMedium, release ? 1 : 0);
        }
Exemple #7
0
        public void SetData(ref FORMATETC formatIn, ref STGMEDIUM medium, bool release)
        {
            switch (formatIn.cfFormat)
            {
            case CF.TEXT:
            case CF.UNICODETEXT:
                PlainTextDataObject.SetData(ref formatIn, ref medium, release);
                break;

            default:
                DataObject.SetData(ref formatIn, ref medium, release);
                break;
            }
        }
Exemple #8
0
        public void GetDataHere(ref FORMATETC format, ref STGMEDIUM medium)
        {
            switch (format.cfFormat)
            {
            case CF.TEXT:
            case CF.UNICODETEXT:
                PlainTextDataObject.GetDataHere(ref format, ref medium);
                break;

            default:
                DataObject.GetDataHere(ref format, ref medium);
                break;
            }
        }
        void System.Runtime.InteropServices.ComTypes.IDataObject.GetData(ref FORMATETC formatetc, out STGMEDIUM medium)
        {
            if (formatetc.cfFormat == (Int16)DataFormats.GetFormat(NativeMethods.CFSTR_FILECONTENTS).Id)
            m_lindex = formatetc.lindex;

              medium = new System.Runtime.InteropServices.ComTypes.STGMEDIUM();
              if (GetTymedUseable(formatetc.tymed)) {
            if (formatetc.cfFormat == (Int16)DataFormats.GetFormat(NativeMethods.CFSTR_FILECONTENTS).Id) {
              if ((formatetc.tymed & TYMED.TYMED_ISTREAM) != TYMED.TYMED_NULL) {
            medium.tymed = TYMED.TYMED_ISTREAM;
            // medium.unionmember = Marshal.GetComInterfaceForObject(GetFileContents(this.m_SelectedItems, formatetc.lindex), typeof(IStreamWrapper));
            medium.unionmember = NativeMethods.VirtualAlloc(IntPtr.Zero, new UIntPtr(1), NativeMethods.MEM_COMMIT, NativeMethods.PAGE_READWRITE);
            if (medium.unionmember == IntPtr.Zero) {
              throw new OutOfMemoryException();
            }

            try {
              ((System.Runtime.InteropServices.ComTypes.IDataObject)this).GetDataHere(ref formatetc, ref medium);
              return;
            } catch {
              NativeMethods.VirtualFree(medium.unionmember, new UIntPtr(1), NativeMethods.MEM_DECOMMIT);
              medium.unionmember = IntPtr.Zero;
              throw;
            }
              }
            } else {
              if ((formatetc.tymed & TYMED.TYMED_HGLOBAL) != TYMED.TYMED_NULL) {
            medium.tymed = TYMED.TYMED_HGLOBAL;
            medium.unionmember = NativeMethods.GlobalAlloc(NativeMethods.GHND | NativeMethods.GMEM_DDESHARE, 1);
            if (medium.unionmember == IntPtr.Zero) {
              throw new OutOfMemoryException();
            }

            try {
              ((System.Runtime.InteropServices.ComTypes.IDataObject)this).GetDataHere(ref formatetc, ref medium);
              return;
            } catch {
              NativeMethods.GlobalFree(new HandleRef((STGMEDIUM)medium, medium.unionmember));
              medium.unionmember = IntPtr.Zero;
              throw;
            }
              }
            }
            medium.tymed = formatetc.tymed;
            ((System.Runtime.InteropServices.ComTypes.IDataObject)this).GetDataHere(ref formatetc, ref medium);
              } else {
            Marshal.ThrowExceptionForHR(NativeMethods.DV_E_TYMED);
              }
        }
        ShellItem[] ParseShellIDListArray(ComTypes.IDataObject pDataObj)
        {
            List <ShellItem> result = new List <ShellItem>();

            ComTypes.FORMATETC format = new ComTypes.FORMATETC();
            ComTypes.STGMEDIUM medium = new ComTypes.STGMEDIUM();

            format.cfFormat = (short)User32.RegisterClipboardFormat("Shell IDList Array");
            format.dwAspect = ComTypes.DVASPECT.DVASPECT_CONTENT;
            format.lindex   = 0;
            format.ptd      = IntPtr.Zero;
            format.tymed    = ComTypes.TYMED.TYMED_HGLOBAL;

            pDataObj.GetData(ref format, out medium);
            Kernel32.GlobalLock(medium.unionmember);

            try
            {
                ShellItem parentFolder = null;
                int       count        = Marshal.ReadInt32(medium.unionmember);
                int       offset       = 4;

                for (int n = 0; n <= count; ++n)
                {
                    int pidlOffset  = Marshal.ReadInt32(medium.unionmember, offset);
                    int pidlAddress = (int)medium.unionmember + pidlOffset;

                    if (n == 0)
                    {
                        parentFolder = new ShellItem(new IntPtr(pidlAddress));
                    }
                    else
                    {
                        result.Add(new ShellItem(parentFolder, new IntPtr(pidlAddress)));
                    }

                    offset += 4;
                }
            }
            finally
            {
                Marshal.FreeHGlobal(medium.unionmember);
            }

            return(result.ToArray());
        }
Exemple #11
0
        void OleInterop.IDataObject.SetData(OleInterop.FORMATETC[] pFormatetc, OleInterop.STGMEDIUM[] pmedium, int fRelease)
        {
            if (null != oleData)
            {
                oleData.SetData(pFormatetc, pmedium, fRelease);
                return;
            }

            if ((null == pFormatetc) || (1 != pFormatetc.Length) ||
                (null == pmedium) || (1 != pmedium.Length))
            {
                throw new ArgumentException();
            }

            BclComTypes.FORMATETC bclFormat = StructConverter.OleFormatETC2Bcl(ref pFormatetc[0]);
            BclComTypes.STGMEDIUM bclMedium = StructConverter.OleSTGMEDIUM2Bcl(ref pmedium[0]);
            bclData.SetData(ref bclFormat, ref bclMedium, (fRelease == 0) ? false : true);
        }
Exemple #12
0
 public static object Convert(string format, ref STGMEDIUM medium)
 {
     if (medium.unionmember != IntPtr.Zero)
     {
         if (medium.tymed == TYMED.TYMED_HGLOBAL)
         {
             return ConvertHandle(format, new HandleRef(format, medium.unionmember));
         }
         if (medium.tymed == TYMED.TYMED_ISTREAM)
         {
             return ConvertStream(format, new HandleRef(format, medium.unionmember));
         }
         if (medium.tymed == TYMED.TYMED_GDI)
         {
             return ConvertBitmap(new HandleRef(format, medium.unionmember));
         }
     }
     return null;
 }
Exemple #13
0
        void IBclAdviseSink.OnDataChange(ref BclComTypes.FORMATETC format, ref BclComTypes.STGMEDIUM stgmedium)
        {
            if (null != bclSink)
            {
                bclSink.OnDataChange(ref format, ref stgmedium);
            }
            else
            {
                // As in the previous case we have to copy the parameters.
                OleInterop.FORMATETC[] pFormatetc = new OleInterop.FORMATETC[1];
                pFormatetc[0] = StructConverter.BclFormatETC2Ole(ref format);

                OleInterop.STGMEDIUM[] pStgmed = new OleInterop.STGMEDIUM[1];
                pStgmed[0] = StructConverter.BclSTGMEDIUM2Ole(ref stgmedium);

                // Call the original interface.
                oleSink.OnDataChange(pFormatetc, pStgmed);
            }
        }
Exemple #14
0
        void OleInterop.IDataObject.GetDataHere(OleInterop.FORMATETC[] pFormatetc, OleInterop.STGMEDIUM[] pRemoteMedium)
        {
            if (null != oleData)
            {
                oleData.GetDataHere(pFormatetc, pRemoteMedium);
                return;
            }

            // Check that the arrays are not null and with only one element.
            if ((null == pFormatetc) || (pFormatetc.Length != 1) ||
                (null == pRemoteMedium) || (pRemoteMedium.Length != 1))
            {
                throw new ArgumentException();
            }

            // Call the method on the BCL interface
            BclComTypes.FORMATETC bclFormat = StructConverter.OleFormatETC2Bcl(ref pFormatetc[0]);
            BclComTypes.STGMEDIUM bclMedium = StructConverter.OleSTGMEDIUM2Bcl(ref pRemoteMedium[0]);
            bclData.GetDataHere(ref bclFormat, ref bclMedium);
            pRemoteMedium[0] = StructConverter.BclSTGMEDIUM2Ole(ref bclMedium);
        }
Exemple #15
0
        void GetData(ref FORMATETC formatetc, out STGMEDIUM medium)
        {
            if (formatetc.cfFormat == (Int16)DataFormats.GetFormat(NativeMethods.CFSTR_FILECONTENTS).Id)
            {
                m_lindex = formatetc.lindex;
            }

            medium = new System.Runtime.InteropServices.ComTypes.STGMEDIUM();
            if (GetTymedUseable(formatetc.tymed))
            {
                if ((formatetc.tymed & TYMED.TYMED_HGLOBAL) != TYMED.TYMED_NULL)
                {
                    medium.tymed       = TYMED.TYMED_HGLOBAL;
                    medium.unionmember = NativeMethods.GlobalAlloc(NativeMethods.GHND | NativeMethods.GMEM_DDESHARE, 1);
                    if (medium.unionmember == IntPtr.Zero)
                    {
                        throw new OutOfMemoryException();
                    }
                    try
                    {
                        ((System.Runtime.InteropServices.ComTypes.IDataObject) this).GetDataHere(ref formatetc, ref medium);
                        return;
                    }
                    catch
                    {
                        NativeMethods.GlobalFree(new HandleRef((STGMEDIUM)medium, medium.unionmember));
                        medium.unionmember = IntPtr.Zero;
                        throw;
                    }
                }
                medium.tymed = formatetc.tymed;
                ((System.Runtime.InteropServices.ComTypes.IDataObject) this).GetDataHere(ref formatetc, ref medium);
            }
            else
            {
                Marshal.ThrowExceptionForHR(NativeMethods.DV_E_TYMED);
            }
        }
Exemple #16
0
        void System.Runtime.InteropServices.ComTypes.IDataObject.GetData(ref System.Runtime.InteropServices.ComTypes.FORMATETC formatetc, out System.Runtime.InteropServices.ComTypes.STGMEDIUM medium)
        {
            if (formatetc.cfFormat == (Int16)DataFormats.GetFormat(Win32.NativeMethods.CFSTR_FILECONTENTS).Id)
                m_lindex = formatetc.lindex;

            medium = new System.Runtime.InteropServices.ComTypes.STGMEDIUM();
            if (GetTymedUseable(formatetc.tymed))
            {
                if ((formatetc.tymed & TYMED.TYMED_HGLOBAL) != TYMED.TYMED_NULL)
                {
                    medium.tymed = TYMED.TYMED_HGLOBAL;
                    medium.unionmember = Win32.NativeMethods.GlobalAlloc(Win32.NativeMethods.GHND | Win32.NativeMethods.GMEM_DDESHARE, 1);
                    if (medium.unionmember == IntPtr.Zero)
                    {
                        throw new OutOfMemoryException();
                    }
                    try
                    {
                        ((System.Runtime.InteropServices.ComTypes.IDataObject)this).GetDataHere(ref formatetc, ref medium);
                        return;
                    }
                    catch
                    {
                        Win32.NativeMethods.GlobalFree(new HandleRef((STGMEDIUM)medium, medium.unionmember));
                        medium.unionmember = IntPtr.Zero;
                        throw;
                    }
                }
                medium.tymed = formatetc.tymed;
                ((System.Runtime.InteropServices.ComTypes.IDataObject)this).GetDataHere(ref formatetc, ref medium);
            }
            else
            {
                Marshal.ThrowExceptionForHR(Win32.NativeMethods.DV_E_TYMED);
            }
        }
Exemple #17
0
 private static void GetMediumFromObject(object data, out STGMEDIUM medium)
 {
     MemoryStream memoryStream = new MemoryStream();
     memoryStream.Write(DataObjectExtensions.ManagedDataStamp.ToByteArray(), 0, Marshal.SizeOf(typeof(Guid)));
     BinaryFormatter binaryFormatter = new BinaryFormatter();
     binaryFormatter.Serialize((Stream)memoryStream, (object)data.GetType());
     binaryFormatter.Serialize((Stream)memoryStream, DataObjectExtensions.GetAsSerializable(data));
     byte[] buffer = memoryStream.GetBuffer();
     IntPtr num = Marshal.AllocHGlobal(buffer.Length);
     try
     {
         Marshal.Copy(buffer, 0, num, buffer.Length);
     }
     catch
     {
         Marshal.FreeHGlobal(num);
         throw;
     }
     medium.unionmember = num;
     medium.tymed = TYMED.TYMED_HGLOBAL;
     medium.pUnkForRelease = (object)null;
 }
        void System.Runtime.InteropServices.ComTypes.IDataObject.GetData(ref FORMATETC formatetc, out STGMEDIUM medium)
        {
            if (formatetc.cfFormat == (Int16)DataFormats.GetFormat(NativeMethods.CFSTR_FILECONTENTS).Id)
            {
                m_lindex = formatetc.lindex;
            }

            medium = new System.Runtime.InteropServices.ComTypes.STGMEDIUM();
            if (GetTymedUseable(formatetc.tymed))
            {
                if (formatetc.cfFormat == (Int16)DataFormats.GetFormat(NativeMethods.CFSTR_FILECONTENTS).Id)
                {
                    if ((formatetc.tymed & TYMED.TYMED_ISTREAM) != TYMED.TYMED_NULL)
                    {
                        medium.tymed = TYMED.TYMED_ISTREAM;
                        // medium.unionmember = Marshal.GetComInterfaceForObject(GetFileContents(this.m_SelectedItems, formatetc.lindex), typeof(IStreamWrapper));
                        medium.unionmember = NativeMethods.VirtualAlloc(IntPtr.Zero, new UIntPtr(1), NativeMethods.MEM_COMMIT, NativeMethods.PAGE_READWRITE);
                        if (medium.unionmember == IntPtr.Zero)
                        {
                            throw new OutOfMemoryException();
                        }

                        try {
                            ((System.Runtime.InteropServices.ComTypes.IDataObject) this).GetDataHere(ref formatetc, ref medium);
                            return;
                        } catch {
                            NativeMethods.VirtualFree(medium.unionmember, new UIntPtr(1), NativeMethods.MEM_DECOMMIT);
                            medium.unionmember = IntPtr.Zero;
                            throw;
                        }
                    }
                }
                else
                {
                    if ((formatetc.tymed & TYMED.TYMED_HGLOBAL) != TYMED.TYMED_NULL)
                    {
                        medium.tymed       = TYMED.TYMED_HGLOBAL;
                        medium.unionmember = NativeMethods.GlobalAlloc(NativeMethods.GHND | NativeMethods.GMEM_DDESHARE, 1);
                        if (medium.unionmember == IntPtr.Zero)
                        {
                            throw new OutOfMemoryException();
                        }

                        try {
                            ((System.Runtime.InteropServices.ComTypes.IDataObject) this).GetDataHere(ref formatetc, ref medium);
                            return;
                        } catch {
                            NativeMethods.GlobalFree(new HandleRef((STGMEDIUM)medium, medium.unionmember));
                            medium.unionmember = IntPtr.Zero;
                            throw;
                        }
                    }
                }
                medium.tymed = formatetc.tymed;
                ((System.Runtime.InteropServices.ComTypes.IDataObject) this).GetDataHere(ref formatetc, ref medium);
            }
            else
            {
                Marshal.ThrowExceptionForHR(NativeMethods.DV_E_TYMED);
            }
        }
Exemple #19
0
 void IComDataObject.GetDataHere(ref FORMATETC formatetc, ref STGMEDIUM medium) {
     Debug.WriteLineIf(CompModSwitches.DataObject.TraceVerbose, "GetDataHere");
     if (innerData is OleConverter) {
         ((OleConverter)innerData).OleDataObject.GetDataHere(ref formatetc, ref medium);
     }
     else {
         GetDataIntoOleStructs(ref formatetc, ref medium);
     }
 }
Exemple #20
0
 private int SaveDataToHandle(object data, string format, ref STGMEDIUM medium) {
     int hr = NativeMethods.E_FAIL;
     if (data is Stream) {
         hr = SaveStreamToHandle(ref medium.unionmember, (Stream)data);
     }
     else if (format.Equals(DataFormats.Text)
              || format.Equals(DataFormats.Rtf)
              || format.Equals(DataFormats.OemText)) {
         hr = SaveStringToHandle(medium.unionmember, data.ToString(), false);
     }
     else if (format.Equals(DataFormats.Html)) {
          hr = SaveHtmlToHandle(medium.unionmember, data.ToString());
     }
     else if (format.Equals(DataFormats.UnicodeText)) {
          hr = SaveStringToHandle(medium.unionmember, data.ToString(), true);
     }
     else if (format.Equals(DataFormats.FileDrop)) {
         hr = SaveFileListToHandle(medium.unionmember, (string[])data);
     }
     else if (format.Equals(CF_DEPRECATED_FILENAME)) {
         string[] filelist = (string[])data;
         hr = SaveStringToHandle(medium.unionmember, filelist[0], false);
     }
     else if (format.Equals(CF_DEPRECATED_FILENAMEW)) {
         string[] filelist = (string[])data;
         hr = SaveStringToHandle(medium.unionmember, filelist[0], true);
     }
     else if (format.Equals(DataFormats.Dib)
              && data is Image) {
         // GDI+ does not properly handle saving to DIB images.  Since the 
         // clipboard will take an HBITMAP and publish a Dib, we don't need
         // to support this.
         //
         hr = DV_E_TYMED; // SaveImageToHandle(ref medium.unionmember, (Image)data);
     }
     else if (format.Equals(DataFormats.Serializable)
              || data is ISerializable 
              || (data != null && data.GetType().IsSerializable)) {
         hr = SaveObjectToHandle(ref medium.unionmember, data);
     }
     return hr;
 }
Exemple #21
0
            /// <include file='doc\DataObject.uex' path='docs/doc[@for="DataObject.OleConverter.GetDataFromOleHGLOBAL"]/*' />
            /// <devdoc>
            ///     Uses HGLOBALs and retrieves the specified format from the bound IComDatabject.
            /// </devdoc>
            /// <internalonly/>
            private Object GetDataFromOleHGLOBAL(string format) {
                Debug.Assert(innerData != null, "You must have an innerData on all DataObjects");

                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_HGLOBAL;

                medium.tymed = TYMED.TYMED_HGLOBAL;

                object data = null;

                if (NativeMethods.S_OK == QueryGetDataUnsafe(ref formatetc)) {
                    try {
                        IntSecurity.UnmanagedCode.Assert();
                        try {
                             innerData.GetData(ref formatetc, out medium);
                        }
                        finally {
                            CodeAccessPermission.RevertAssert();
                        }

                        if (medium.unionmember != IntPtr.Zero) {
                            data = GetDataFromHGLOBLAL(format, medium.unionmember);
                        }
                    }
                    catch {
                    }
                }
                return data;
            }
Exemple #22
0
        /// <include file='doc\DataObject.uex' path='docs/doc[@for="DataObject.GetDataIntoOleStructs"]/*' />
        /// <devdoc>
        ///     Populates Ole datastructes from a [....] dataObject. This is the core
        ///     of [....] to OLE conversion.
        /// </devdoc>
        /// <internalonly/>
        private void GetDataIntoOleStructs(ref FORMATETC formatetc,
                                           ref STGMEDIUM medium) {

            if (GetTymedUseable(formatetc.tymed) && GetTymedUseable(medium.tymed)) {
                string format = DataFormats.GetFormat(formatetc.cfFormat).Name;

                if (GetDataPresent(format)) {
                    Object data = GetData(format);                    

                    if ((formatetc.tymed & TYMED.TYMED_HGLOBAL) != 0) {
                        int hr = SaveDataToHandle(data, format, ref medium);
                        if (NativeMethods.Failed(hr)) {
                            Marshal.ThrowExceptionForHR(hr);
                        }
                    }
                    else if ((formatetc.tymed & TYMED.TYMED_GDI) != 0) {
                        if (format.Equals(DataFormats.Bitmap) && data is Bitmap) {
                            // save bitmap
                            //
                            Bitmap bm = (Bitmap)data;
                            if (bm != null) {
                                medium.unionmember = GetCompatibleBitmap(bm); // gpr: Does this get properly disposed?
                            }
                        }
                    }
/* gpr
                    else if ((formatetc.tymed & TYMED.TYMED_ENHMF) != 0) {
                        if (format.Equals(DataFormats.EnhancedMetafile)
                            && data is Metafile) {
                            // save metafile

                            Metafile mf = (Metafile)data;
                            if (mf != null) {
                                medium.unionmember = mf.Handle;
                            }
                        }
                    } 
                    */
                    else {
                        Marshal.ThrowExceptionForHR (DV_E_TYMED);
                    }
                }
                else {
                    Marshal.ThrowExceptionForHR (DV_E_FORMATETC);
                }
            }
            else {
                Marshal.ThrowExceptionForHR (DV_E_TYMED);
            }
        }
 /// <summary>
 /// Handles DataChanged events from a COM IDataObject.
 /// </summary>
 /// <param name="format">The data format that had a change.</param>
 /// <param name="stgmedium">The data value.</param>
 public void OnDataChange(ref FORMATETC format, ref STGMEDIUM stgmedium)
 {
     // We listen to DropDescription changes, so that we can unset the IsDefault
     // drop description flag.
     var odd = DropDescriptionHelper.GetDropDescription(m_data);
     if (odd != null)
     {
         DropDescriptionHelper.SetDropDescriptionIsDefault(m_data, false);
     }
 }
Exemple #24
0
 /// <summary>
 /// Internal implementation of the GetDataHere procedure. It is not neccessary to catch exceptions into this implementations, since the exceptions are catched and reported
 /// in the outer <see cref="GetDataHere"/> function.
 /// </summary>
 /// <param name="format">The format.</param>
 /// <param name="medium">The medium.</param>
 /// <returns><c>True</c> if the data could be provided, otherwise <c>False</c>.</returns>
 protected abstract bool InternalGetDataHere(ref System.Runtime.InteropServices.ComTypes.FORMATETC format, ref System.Runtime.InteropServices.ComTypes.STGMEDIUM medium);
        private ShellObject[] ParseShellIDListArray(System.Runtime.InteropServices.ComTypes.IDataObject pDataObj)
        {
            List<ShellObject> result = new List<ShellObject>();
            System.Runtime.InteropServices.ComTypes.FORMATETC format = new System.Runtime.InteropServices.ComTypes.FORMATETC();
            System.Runtime.InteropServices.ComTypes.STGMEDIUM medium = new System.Runtime.InteropServices.ComTypes.STGMEDIUM();

            format.cfFormat = (short)ExplorerBrowser.RegisterClipboardFormat("Shell IDList Array");
            format.dwAspect = System.Runtime.InteropServices.ComTypes.DVASPECT.DVASPECT_CONTENT;
            format.lindex = 0;
            format.ptd = IntPtr.Zero;
            format.tymed = System.Runtime.InteropServices.ComTypes.TYMED.TYMED_HGLOBAL;

            pDataObj.GetData(ref format, out medium);
            ExplorerBrowser.GlobalLock(medium.unionmember);

            try
            {
                ShellObject parentFolder = null;
                int count = Marshal.ReadInt32(medium.unionmember);
                int offset = 4;

                for (int n = 0; n <= count; ++n)
                {
                    int pidlOffset = Marshal.ReadInt32(medium.unionmember, offset);
                    int pidlAddress = (int)medium.unionmember + pidlOffset;

                    if (n == 0)
                    {
                        parentFolder = ShellObjectFactory.Create(new IntPtr(pidlAddress));
                    }
                    else
                    {
                        result.Add(ShellObjectFactory.Create(ExplorerBrowser.CreateItemWithParent(GetIShellFolder(parentFolder.NativeShellItem), new IntPtr(pidlAddress))));
                    }

                    offset += 4;
                }
            }
            finally
            {
                Marshal.FreeHGlobal(medium.unionmember);
            }

            return result.ToArray();
        }
Exemple #26
0
 public static extern void ReleaseStgMedium(
     [In, MarshalAs(UnmanagedType.Struct)]
     ref System.Runtime.InteropServices.ComTypes.STGMEDIUM pmedium);
 public void SetData(ref FORMATETC formatIn, ref STGMEDIUM medium, bool release)
 {
     throw new NotImplementedException();
 }
 public void GetDataHere(ref FORMATETC format, ref STGMEDIUM medium)
 {
     throw new NotImplementedException();
 }
Exemple #29
0
        void System.Runtime.InteropServices.ComTypes.IDataObject.GetData(ref System.Runtime.InteropServices.ComTypes.FORMATETC formatetc, out System.Runtime.InteropServices.ComTypes.STGMEDIUM medium)
        {
            try
            {
                medium = new System.Runtime.InteropServices.ComTypes.STGMEDIUM();

                if (formatetc.cfFormat == (Int16)DataFormats.GetFormat(NativeMethods.CFSTR_FILECONTENTS).Id)
                {
                    m_lindex = formatetc.lindex;
                }

                if (GetTymedUseable(formatetc.tymed))
                {
                    if ((formatetc.tymed & TYMED.TYMED_ISTREAM) != TYMED.TYMED_NULL)
                    {
                        if (objectType != ClipboardDataType.File)
                        {
                            return;
                        }

                        try
                        {
                            //DropSuccess?.Invoke(this, null);
                            medium.tymed = TYMED.TYMED_ISTREAM;
                            IStream o = (IStream)GetData("FileContents", false);
                            medium.unionmember = Marshal.GetComInterfaceForObject(o, typeof(IStream));
                            return;
                        }
                        catch (Exception ex)
                        {
                            //ISLogger.Write("InputshareDataObject: Get FileContents failed: " + ex.Message);
                            return;
                        }
                    }
                    else if ((formatetc.tymed & TYMED.TYMED_HGLOBAL) != TYMED.TYMED_NULL)
                    {
                        medium.tymed       = TYMED.TYMED_HGLOBAL;
                        medium.unionmember = NativeMethods.GlobalAlloc(NativeMethods.GHND | NativeMethods.GMEM_DDESHARE, 1);
                        if (medium.unionmember == IntPtr.Zero)
                        {
                            throw new OutOfMemoryException();
                        }
                        try
                        {
                            ((System.Runtime.InteropServices.ComTypes.IDataObject) this).GetDataHere(ref formatetc, ref medium);
                            return;
                        }
                        catch
                        {
                            NativeMethods.GlobalFree(new HandleRef((STGMEDIUM)medium, medium.unionmember));
                            medium.unionmember = IntPtr.Zero;
                            return;
                        }
                    }
                    medium.tymed = formatetc.tymed;
                    ((System.Runtime.InteropServices.ComTypes.IDataObject) this).GetDataHere(ref formatetc, ref medium);
                }
                else
                {
                    Marshal.ThrowExceptionForHR(NativeMethods.DV_E_TYMED);
                }
            }catch (Exception ex)
            {
                medium = new STGMEDIUM();
                ISLogger.Write("InputshareDataObject: " + ex.Message);
            }
        }
        /// <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.GetFormat(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.GetFormat((short)formatetc.cfFormat).Name, medium.unionmember });
            }

            return null;
        }
 public static extern HRESULT CopyStgMedium(ref STGMEDIUM pcstgmedSrc, ref STGMEDIUM pstgmedDest);
Exemple #32
0
            /// <include file='doc\DataObject.uex' path='docs/doc[@for="DataObject.OleConverter.GetDataFromOleIStream"]/*' />
            /// <devdoc>
            ///     Uses IStream and retrieves the specified format from the bound IComDataObject.
            /// </devdoc>
            /// <internalonly/>
            private 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;

                medium.tymed = TYMED.TYMED_ISTREAM;

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

                try {
                    IntSecurity.UnmanagedCode.Assert();
                    try {
                         innerData.GetData(ref formatetc, out medium);
                    }
                    finally {
                        CodeAccessPermission.RevertAssert();
                    }
                }
                catch {
                    return null;
                }

                if (medium.unionmember != IntPtr.Zero) {
                    UnsafeNativeMethods.IStream pStream = (UnsafeNativeMethods.IStream)Marshal.GetObjectForIUnknown(medium.unionmember);
                    Marshal.Release(medium.unionmember);
                    NativeMethods.STATSTG sstg = new NativeMethods.STATSTG();
                    pStream.Stat(sstg, NativeMethods.STATFLAG_DEFAULT );
                    int size = (int)sstg.cbSize;

                    IntPtr hglobal = UnsafeNativeMethods.GlobalAlloc(NativeMethods.GMEM_MOVEABLE
                                                      | NativeMethods.GMEM_DDESHARE
                                                      | NativeMethods.GMEM_ZEROINIT,
                                                      size);
                    IntPtr ptr = UnsafeNativeMethods.GlobalLock(new HandleRef(innerData, hglobal));
                    pStream.Read(ptr, size);
                    UnsafeNativeMethods.GlobalUnlock(new HandleRef(innerData, hglobal));

                    return GetDataFromHGLOBLAL(format, hglobal);
                }

                return null;
            }
Exemple #33
0
        protected override bool InternalGetDataHere(ref System.Runtime.InteropServices.ComTypes.FORMATETC format, ref System.Runtime.InteropServices.ComTypes.STGMEDIUM medium)
        {
            if (format.cfFormat == DataObjectHelper.CF_EMBEDSOURCE && (format.tymed & TYMED.TYMED_ISTORAGE) != 0)
            {
                medium.tymed          = TYMED.TYMED_ISTORAGE;
                medium.pUnkForRelease = null;
                var stg = (IStorage)Marshal.GetObjectForIUnknown(medium.unionmember);
                // we don't save the document directly, since this would mean to save the whole (and probably huge) project
                // instead we first make a mini project with the neccessary data only and then save this instead
                InternalSaveMiniProject(stg, _altaxoMiniProject, _graphDocumentName);
                return(true);
            }

            if (format.cfFormat == DataObjectHelper.CF_LINKSOURCE && (format.tymed & TYMED.TYMED_ISTREAM) != 0)
            {
                // we should make sure that ComManager is already started, so that the moniker can be used by the program
                if (!_comManager.IsActive)
                {
                    _comManager.StartLocalServer();
                }

                IMoniker documentMoniker = CreateNewDocumentMoniker();

                if (null != documentMoniker)
                {
                    medium.tymed          = TYMED.TYMED_ISTREAM;
                    medium.pUnkForRelease = null;
                    var strm = (IStream)Marshal.GetObjectForIUnknown(medium.unionmember);
                    DataObjectHelper.SaveMonikerToStream(documentMoniker, strm);
                    return(true);
                }
            }

            return(false);
        }
Exemple #34
0
            /// <include file='doc\DataObject.uex' path='docs/doc[@for="DataObject.OleConverter.GetDataFromOleOther"]/*' />
            /// <devdoc>
            ///     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.
            /// </devdoc>
            /// <internalonly/>
            private Object GetDataFromOleOther(string format) {
                Debug.Assert(innerData != 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;
                }
                else if (format.Equals(DataFormats.EnhancedMetafile)) {
                    tymed = TYMED.TYMED_ENHMF;
                }

                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;
                medium.tymed = tymed;

                Object data = null;
                if (NativeMethods.S_OK == QueryGetDataUnsafe(ref formatetc)) {
                    try {
                        IntSecurity.UnmanagedCode.Assert();
                        try {
                             innerData.GetData(ref formatetc, out medium);
                        }
                        finally {
                            CodeAccessPermission.RevertAssert();
                        }
                    }
                    catch {
                    }
                }

                if (medium.unionmember != IntPtr.Zero) {

                    if (format.Equals(DataFormats.Bitmap)
                        //||format.Equals(DataFormats.Dib))
                    ) { 
                        // as/urt 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 tbe 
                        //clipboard. We call Add here, since DeleteObject calls Remove.
                        System.Internal.HandleCollector.Add(medium.unionmember, NativeMethods.CommonHandles.GDI);
                        Image clipboardImage = null;
                        IntSecurity.ObjectFromWin32Handle.Assert();
                        try
                        {
                            clipboardImage = Image.FromHbitmap(medium.unionmember);
                        }
                        finally
                        {
                            CodeAccessPermission.RevertAssert();
                        }
                        if (clipboardImage != null) {
                            Image firstImage = clipboardImage;
                            clipboardImage = (Image)clipboardImage.Clone();
                            SafeNativeMethods.DeleteObject(new HandleRef(null, medium.unionmember));
                            firstImage.Dispose();
                        }
                        data = clipboardImage;
                    }
/* gpr:
                    else if (format.Equals(DataFormats.EnhancedMetafile)) {
                        data = new Metafile(medium.unionmember);
                    }
*/
                }

                return data;
            }
Exemple #35
0
        internal static void GetSelectedItems(IntPtr pidlFolder, IntPtr pDataObj, IntPtr hKeyProgID, ref List<String> SelectedItems, ref bool isClickOnEmptyArea)
        {
            if (pDataObj == IntPtr.Zero && pidlFolder == IntPtr.Zero)
                throw new ArgumentException();
            else if (pDataObj == IntPtr.Zero)
            {
                //User Click on Empty Area of a Folder, pDataObj is empty while pidlFolder is the current path
                StringBuilder sb = new StringBuilder(260);
                if (!NativeMethods.SHGetPathFromIDListW(pidlFolder, sb))
                    Marshal.ThrowExceptionForHR(WinError.E_FAIL);
                else
                {
                    isClickOnEmptyArea = true;
                    SelectedItems = new List<string>();
                    SelectedItems.Add(sb.ToString());
                }
            }
            else
            {
                //User actually select some item, pDataObj is the list while pidlFolder is empty
                isClickOnEmptyArea = false;

                FORMATETC fe = new FORMATETC();
                fe.cfFormat = (short)CLIPFORMAT.CF_HDROP;
                fe.ptd = IntPtr.Zero;
                fe.dwAspect = DVASPECT.DVASPECT_CONTENT;
                fe.lindex = -1;
                fe.tymed = TYMED.TYMED_HGLOBAL;
                STGMEDIUM stm = new STGMEDIUM();

                IDataObject dataObject = (IDataObject)Marshal.GetObjectForIUnknown(pDataObj);
                dataObject.GetData(ref fe, out stm);

                try
                {
                    IntPtr hDrop = stm.unionmember;
                    if (hDrop == IntPtr.Zero)
                        throw new ArgumentException();

                    uint nFiles = NativeMethods.DragQueryFile(hDrop, UInt32.MaxValue, null, 0);

                    if (nFiles == 0)
                        Marshal.ThrowExceptionForHR(WinError.E_FAIL);

                    SelectedItems = new List<string>();

                    for (int i = 0; i < nFiles; i++)
                    {
                        StringBuilder sb = new StringBuilder(260);
                        if (NativeMethods.DragQueryFile(hDrop, (uint)i, sb, sb.Capacity) == 0)
                            Marshal.ThrowExceptionForHR(WinError.E_FAIL);
                        else
                            SelectedItems.Add(sb.ToString());
                    }
                }
                finally
                {
                    NativeMethods.ReleaseStgMedium(ref stm);
                }
            }
        }
Exemple #36
0
        void IComDataObject.GetData(ref FORMATETC formatetc, out STGMEDIUM medium) {
            Debug.WriteLineIf(CompModSwitches.DataObject.TraceVerbose, "GetData");
            if (innerData is OleConverter) {
                ((OleConverter)innerData).OleDataObject.GetData(ref formatetc, out medium);
                return;
            }

            medium = new STGMEDIUM();

            if (GetTymedUseable(formatetc.tymed)) {
                if ((formatetc.tymed & TYMED.TYMED_HGLOBAL) != 0) {
                    medium.tymed = TYMED.TYMED_HGLOBAL;
                    medium.unionmember = UnsafeNativeMethods.GlobalAlloc(NativeMethods.GMEM_MOVEABLE
                                                             | NativeMethods.GMEM_DDESHARE
                                                             | NativeMethods.GMEM_ZEROINIT,
                                                             1);
                    if (medium.unionmember == IntPtr.Zero) {
                        throw new OutOfMemoryException();
                    }
 
                    try {
                        ((IComDataObject)this).GetDataHere(ref formatetc, ref medium);
                    }
                    catch {
                        UnsafeNativeMethods.GlobalFree(new HandleRef(medium, medium.unionmember));
                        medium.unionmember = IntPtr.Zero;
                        throw;
                    }
                }
                else {
                    medium.tymed  = formatetc.tymed;
                    ((IComDataObject)this).GetDataHere(ref formatetc, ref medium);
                }
            }
            else {
                Marshal.ThrowExceptionForHR(DV_E_TYMED);
            }
        }
Exemple #37
0
		public void GetData(ref FORMATETC format, out STGMEDIUM medium)
		{
			ComDebug.ReportInfo("{0}.IDataObject.GetData({1})", this.GetType().Name, DataObjectHelper.FormatEtcToString(format));

			try
			{
				// Locate the data
				foreach (var rendering in Renderings)
				{
					if ((rendering.format.tymed & format.tymed) > 0
							&& rendering.format.dwAspect == format.dwAspect
							&& rendering.format.cfFormat == format.cfFormat
							&& rendering.renderer != null)
					{
						// Found it. Return a copy of the data.

						medium = new STGMEDIUM();
						medium.tymed = rendering.format.tymed & format.tymed;
						medium.unionmember = rendering.renderer(medium.tymed);
						if (medium.tymed == TYMED.TYMED_ISTORAGE || medium.tymed == TYMED.TYMED_ISTREAM)
							medium.pUnkForRelease = Marshal.GetObjectForIUnknown(medium.unionmember);
						else
							medium.pUnkForRelease = null;
						return;
					}
				}
			}
			catch (Exception e)
			{
				ComDebug.ReportError("{0}.IDataObject.GetData threw an exception {1}", this.GetType().Name, e);
				throw;
			}

			ComDebug.ReportInfo("{0}.IDataObject.GetData, no data delivered!", this.GetType().Name);
			medium = new STGMEDIUM();
			// Marshal.ThrowExceptionForHR(ComReturnValue.DV_E_FORMATETC);
		}
Exemple #38
0
        void IComDataObject.SetData(ref FORMATETC pFormatetcIn, ref STGMEDIUM pmedium, bool fRelease) {

            Debug.WriteLineIf(CompModSwitches.DataObject.TraceVerbose, "SetData");
            if (innerData is OleConverter) {
                ((OleConverter)innerData).OleDataObject.SetData(ref pFormatetcIn, ref pmedium, fRelease);
                return;
            }
            // 

            throw new NotImplementedException();
        }
Exemple #39
0
		public void SetData(ref FORMATETC formatIn, ref STGMEDIUM medium, bool release)
		{
			ComDebug.ReportError("{0}.IDataObject.SetData - NOT SUPPORTED!", this.GetType().Name);
			throw new NotSupportedException();
		}
Exemple #40
0
 public void OnDataChange(ref FORMATETC format, ref STGMEDIUM stgmedium)
 {
     if (DataObjectExtensions.GetDropDescription(this.data) == null)
         return;
     DataObjectExtensions.SetDropDescriptionIsDefault(this.data, false);
 }
Exemple #41
0
 protected override bool InternalGetDataHere(ref System.Runtime.InteropServices.ComTypes.FORMATETC format, ref System.Runtime.InteropServices.ComTypes.STGMEDIUM medium)
 {
     if (format.cfFormat == DataObjectHelper.CF_LINKSOURCE && (format.tymed & TYMED.TYMED_ISTREAM) != 0)
     {
         var moniker = Moniker;
         if (null != moniker)
         {
             medium.tymed          = TYMED.TYMED_ISTREAM;
             medium.pUnkForRelease = null;
             var strm = (IStream)Marshal.GetObjectForIUnknown(medium.unionmember);
             DataObjectHelper.SaveMonikerToStream(Moniker, strm);
             return(true);
         }
     }
     return(false);
 }
		private static extern void ReleaseStgMedium(ref STGMEDIUM pmedium);
 private static extern void ReleaseStgMedium(ref STGMEDIUM pmedium);
 internal static extern void ReleaseStgMedium(ref STGMEDIUM medium);
        /// <summary>
        /// Serializes managed data to an HGLOBAL.
        /// </summary>
        /// <param name="data">The managed data object.</param>
        /// <returns>An STGMEDIUM pointing to the allocated HGLOBAL.</returns>
        private static void GetMediumFromObject(object data, out STGMEDIUM medium)
        {
            // We'll serialize to a managed stream temporarily
            MemoryStream stream = new MemoryStream();

            // Write an indentifying stamp, so we can recognize this as custom
            // marshaled data.
            stream.Write(ManagedDataStamp.ToByteArray(), 0, Marshal.SizeOf(typeof(Guid)));

            // Now serialize the data. Note, if the data is not directly serializable,
            // we'll try type conversion. Also, we serialize the type. That way,
            // during deserialization, we know which type to convert back to, if
            // appropriate.
            BinaryFormatter formatter = new BinaryFormatter();
            formatter.Serialize(stream, data.GetType());
            formatter.Serialize(stream, GetAsSerializable(data));

            // Now copy to an HGLOBAL
            byte[] bytes = stream.GetBuffer();
            IntPtr p = Marshal.AllocHGlobal(bytes.Length);
            try
            {
                Marshal.Copy(bytes, 0, p, bytes.Length);
            }
            catch
            {
                // Make sure to free the memory on exceptions
                Marshal.FreeHGlobal(p);
                throw;
            }

            // Now allocate an STGMEDIUM to wrap the HGLOBAL
            medium.unionmember = p;
            medium.tymed = ComTypes.TYMED.TYMED_HGLOBAL;
            medium.pUnkForRelease = null;
        }
Exemple #46
0
 public void GetDataHere(ref System.Runtime.InteropServices.ComTypes.FORMATETC format, ref System.Runtime.InteropServices.ComTypes.STGMEDIUM medium)
 {
     ComDebug.ReportInfo("{0}.IDataObject.GetDataHere({1})", GetType().Name, DataObjectHelper.ClipboardFormatName(format.cfFormat));
     // Allows containers to duplicate this into their own storage.
     try
     {
         if (InternalGetDataHere(ref format, ref medium))
         {
             return; // data could be provided
         }
     }
     catch (Exception e)
     {
         ComDebug.ReportError("{0}.IDataObject.GetDataHere threw an exception: {1}", GetType().Name, e);
         throw;
     }
     Marshal.ThrowExceptionForHR(ComReturnValue.DATA_E_FORMATETC);
 }
Exemple #47
0
        private void InsertEmbeddedAtPosition(TextPointer position, IComDataObject data, out UnsafeNativeMethods.TS_TEXTCHANGE change)
        {
            SecurityHelper.DemandUnmanagedCode();

            ITextContainer container;
            // Get enhanced metafile handle from IOleDataObject.
            FORMATETC formatetc = new FORMATETC();
            STGMEDIUM stgmedium = new STGMEDIUM();
            formatetc.cfFormat = NativeMethods.CF_ENHMETAFILE;
            formatetc.ptd = IntPtr.Zero;
            formatetc.dwAspect = DVASPECT.DVASPECT_CONTENT;
            formatetc.lindex = -1;
            formatetc.tymed = TYMED.TYMED_ENHMF;
            stgmedium.tymed = TYMED.TYMED_ENHMF;

            data.GetData(ref formatetc, out stgmedium);

            if (stgmedium.unionmember == IntPtr.Zero)
            {
                throw new COMException(SR.Get(SRID.TextStore_BadObjectData), NativeMethods.E_INVALIDARG);
            }

            IntPtr hbitmap = SystemDrawingHelper.ConvertMetafileToHBitmap(stgmedium.unionmember);

            // create a InkInteropObject framework element.
            InkInteropObject inkobject = new InkInteropObject(data);

            inkobject.Source = Imaging.CreateBitmapSourceFromHBitmap(hbitmap, IntPtr.Zero, Int32Rect.Empty, null);

            position = InsertInkAtPosition(position, inkobject, out change);

            // Move the selection.
            container = this.TextContainer;
            TextSelection.SetCaretToPosition(position, LogicalDirection.Backward, /*allowStopAtLineEnd:*/false, /*allowStopNearSpace:*/false);
        }
Exemple #48
0
        /// <summary>
        /// Initialize the context menu handler.
        /// </summary>
        /// <param name="pidlFolder">
        /// A pointer to an ITEMIDLIST structure that uniquely identifies a folder.
        /// </param>
        /// <param name="pDataObj">
        /// A pointer to an IDataObject interface object that can be used to retrieve 
        /// the objects being acted upon.
        /// </param>
        /// <param name="hKeyProgID">
        /// The registry key for the file object or folder type.
        /// </param>
        public void Initialize(IntPtr pidlFolder, IntPtr pDataObj, IntPtr hKeyProgID)
        {
            if (pDataObj == IntPtr.Zero)
            {
                throw new ArgumentException();
            }

            FORMATETC fe = new FORMATETC();
            fe.cfFormat = (short)CLIPFORMAT.CF_HDROP;
            fe.ptd = IntPtr.Zero;
            fe.dwAspect = DVASPECT.DVASPECT_CONTENT;
            fe.lindex = -1;
            fe.tymed = TYMED.TYMED_HGLOBAL;
            STGMEDIUM stm = new STGMEDIUM();

            // The pDataObj pointer contains the objects being acted upon. In this 
            // example, we get an HDROP handle for enumerating the selected files 
            // and folders.
            IDataObject dataObject = (IDataObject)Marshal.GetObjectForIUnknown(pDataObj);
            dataObject.GetData(ref fe, out stm);

            try
            {
                // Get an HDROP handle.
                IntPtr hDrop = stm.unionmember;
                if (hDrop == IntPtr.Zero)
                {
                    throw new ArgumentException();
                }

                // Determine how many files are involved in this operation.
                uint nFiles = NativeMethods.DragQueryFile(hDrop, UInt32.MaxValue, null, 0);

                // This code sample displays the custom context menu item when only 
                // one file is selected. 
                if (nFiles == 1)
                {
                    // Get the path of the file.
                    StringBuilder fileName = new StringBuilder(260);
                    if (0 == NativeMethods.DragQueryFile(hDrop, 0, fileName,
                        fileName.Capacity))
                    {
                        Marshal.ThrowExceptionForHR(WinError.E_FAIL);
                    }
                    this.selectedFile = fileName.ToString();
                }
                else
                {
                    Marshal.ThrowExceptionForHR(WinError.E_FAIL);
                }

                // [-or-]

                // Enumerate the selected files and folders.
                //if (nFiles > 0)
                //{
                //    StringCollection selectedFiles = new StringCollection();
                //    StringBuilder fileName = new StringBuilder(260);
                //    for (uint i = 0; i < nFiles; i++)
                //    {
                //        // Get the next file name.
                //        if (0 != NativeMethods.DragQueryFile(hDrop, i, fileName,
                //            fileName.Capacity))
                //        {
                //            // Add the file name to the list.
                //            selectedFiles.Add(fileName.ToString());
                //        }
                //    }
                //
                //    // If we did not find any files we can work with, throw 
                //    // exception.
                //    if (selectedFiles.Count == 0)
                //    {
                //        Marshal.ThrowExceptionForHR(WinError.E_FAIL);
                //    }
                //}
                //else
                //{
                //    Marshal.ThrowExceptionForHR(WinError.E_FAIL);
                //}
            }
            finally
            {
                NativeMethods.ReleaseStgMedium(ref stm);
            }
        }
Exemple #49
0
        protected override bool InternalGetDataHere(ref System.Runtime.InteropServices.ComTypes.FORMATETC format, ref System.Runtime.InteropServices.ComTypes.STGMEDIUM medium)
        {
            if (format.cfFormat == DataObjectHelper.CF_EMBEDSOURCE && (format.tymed & TYMED.TYMED_ISTORAGE) != 0)
            {
                medium.tymed          = TYMED.TYMED_ISTORAGE;
                medium.pUnkForRelease = null;
                var stg = (IStorage)Marshal.GetObjectForIUnknown(medium.unionmember);

                Save(stg, false);
                return(true);
            }

            return(false);
        }
 public static extern void ReleaseStgMedium(ref STGMEDIUM pmedium);
        // Get this clipboard format out of this data object
        public static byte[] GetData(IDataObject oData, string cfFormat)
        {
            // First, we try using the built-in functionality. Unfortunately, in the TYMED_ISTREAM case
            // they forget to seek the stream to zero, and so aren't successful. We'll take care of that
            // in a moment.
            //
            System.IO.Stream stm = (System.IO.Stream)oData.GetData(cfFormat, false);
            if (null != stm)
                {
                stm.Seek(0, System.IO.SeekOrigin.Begin);
                int    cb  = (int)stm.Length;
                byte[] rgb = new byte[cb];
                int cbRead = stm.Read(rgb, 0, cb);
                if (cbRead == cb)
                    {
                    // The bug is that the data returned is entirely zero. Let's check.
                    //
                    for (int ib=0; ib < cb; ib++)
                        {
                        if (rgb[ib] != 0)
                            return rgb;
                        }
                    }
                }
            //
            // Ok, try to see if we can get it on a stream ourselves
            //
            COMTypes.IDataObject ido       = (COMTypes.IDataObject)oData;
            COMTypes.FORMATETC   formatEtc = new COMTypes.FORMATETC();
            COMTypes.STGMEDIUM   medium    = new COMTypes.STGMEDIUM();
            formatEtc.cfFormat = (short)DataFormats.GetFormat(cfFormat).Id;
            formatEtc.dwAspect = COMTypes.DVASPECT.DVASPECT_CONTENT;
            formatEtc.lindex   = -1;                            // REVIEW: is 0 better?
            formatEtc.tymed    = COMTypes.TYMED.TYMED_ISTREAM;
            //
            ido.GetData(ref formatEtc, out medium);
            //
            if (medium.unionmember != IntPtr.Zero)
                {
                // Get at the IStream and release the ref in the medium
                COMTypes.IStream istm = (COMTypes.IStream)Marshal.GetObjectForIUnknown(medium.unionmember);
                Marshal.Release(medium.unionmember);

                // How big is the stream?
                COMTypes.STATSTG statstg = new COMTypes.STATSTG();
                istm.Stat(out statstg, 1);
                int cb = (int)statstg.cbSize;
                byte[] rgb = new byte[cb];

                // Seek the stream to the beginning and read the data
                IntPtr pcbRead = Marshal.AllocCoTaskMem(sizeof(int));
                istm.Seek(0, 0, IntPtr.Zero);
                istm.Read(rgb, cb, pcbRead);
                int cbRead = Marshal.ReadInt32(pcbRead);
                Marshal.FreeCoTaskMem(pcbRead);

                if (cb==cbRead)
                    return rgb;
                }
            //
            // Can't get the data
            //
            return null;
        }