Example #1
0
        //
        //////////////////////////////////////////////////////////////

        //////////////////////////////////////////////////////////////
        // Next
        int OleInterop.IEnumFORMATETC.Next(uint celt, OleInterop.FORMATETC[] rgelt, uint[] pceltFetched)
        {
            if (null != oleEnum)
            {
                return(oleEnum.Next(celt, rgelt, pceltFetched));
            }

            BclComTypes.FORMATETC[] bclStat = new BclComTypes.FORMATETC[celt];
            int[] fetched = new int[1];
            int   hr      = bclEnum.Next((int)celt, bclStat, fetched);

            if (NativeMethods.Failed(hr))
            {
                return(hr);
            }
            if (null != pceltFetched)
            {
                pceltFetched[0] = (uint)fetched[0];
            }
            for (int i = 0; i < fetched[0]; i++)
            {
                rgelt[i] = StructConverter.BclFormatETC2Ole(ref bclStat[i]);
            }
            return(hr);
        }
Example #2
0
        int OleInterop.IDataObject.DAdvise(OleInterop.FORMATETC[] pFormatetc, uint ADVF, OleInterop.IAdviseSink pAdvSink, out uint pdwConnection)
        {
            if (null != oleData)
            {
                return(oleData.DAdvise(pFormatetc, ADVF, pAdvSink, out pdwConnection));
            }

            // We have to call the method in the BCL version of the interface, so we need to
            // convert the parameters to the other type of structure.

            // As first make sure that the array contains exactly one element.
            if ((null == pFormatetc) || (pFormatetc.Length != 1))
            {
                throw new ArgumentException();
            }

            // Now convert the patameters
            BclComTypes.FORMATETC   bclFormat = StructConverter.OleFormatETC2Bcl(ref pFormatetc[0]);
            BclComTypes.IAdviseSink bclSink   = pAdvSink as BclComTypes.IAdviseSink;
            if (null == bclSink)
            {
                bclSink = new AdviseSink(pAdvSink);
            }

            int connection;
            int hr = bclData.DAdvise(ref bclFormat, (BclComTypes.ADVF)(ADVF), bclSink, out connection);

            pdwConnection = (uint)connection;
            return(hr);
        }
Example #3
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);
            }
        }
        /// <summary>
        /// Creates a connection between a data object and an advisory sink. This method is called by an object
        /// that supports an advisory sink and enables the advisory sink to be notified of changes in the object's data.</summary>
        /// <returns>This method supports the standard return values E_INVALIDARG, E_UNEXPECTED, and E_OUTOFMEMORY,
        /// as well as the following:
        /// ValueDescriptionS_OK -- The advisory connection was created.
        /// E_NOTIMPL -- This method is not implemented on the data object.
        /// DV_E_LINDEX -- There is an invalid value for <see cref="F:System.Runtime.InteropServices.ComTypes.FORMATETC.lindex"/>;
        ///   currently, only -1 is supported.
        /// DV_E_FORMATETC -- There is an invalid value for the <paramref name="pFormatetc"/> parameter.
        /// OLE_E_ADVISENOTSUPPORTED -- The data object does not support change notification.</returns>
        /// <param name="pFormatetc">A <see cref="T:System.Runtime.InteropServices.ComTypes.FORMATETC"/> structure,
        /// passed by reference, that defines the format, target device, aspect, and medium that will be used for
        /// future notifications.</param>
        /// <param name="advf">One of the ADVF values that specifies a group of flags for controlling the advisory
        /// connection.</param>
        /// <param name="adviseSink">A pointer to the IAdviseSink interface on the advisory sink that will receive
        /// the change notification.</param>
        /// <param name="connection">When this method returns, contains a pointer to a DWORD token that identifies
        /// this connection. You can use this token later to delete the advisory connection by passing it to
        /// <see cref="M:System.Runtime.InteropServices.ComTypes.IDataObject.DUnadvise(System.Int32)"/>.
        /// If this value is zero, the connection was not established. This parameter is passed uninitialized.</param>
        public int DAdvise(ref FORMATETC pFormatetc, ADVF advf, IAdviseSink adviseSink, out int connection)
        {
            // Check that the specified advisory flags are supported.
            const ADVF c_advfAllowed = ADVF.ADVF_NODATA | ADVF.ADVF_ONLYONCE | ADVF.ADVF_PRIMEFIRST;
            if ((int)((advf | c_advfAllowed) ^ c_advfAllowed) != 0)
            {
                connection = 0;
                return OLE_E_ADVISENOTSUPPORTED;
            }

            // Create and insert an entry for the connection list
            var entry = new AdviseEntry
            {
                Format = pFormatetc,
                Advf = advf,
                Sink = adviseSink,
            };
            m_connections.Add(m_nextConnectionId, entry);
            connection = m_nextConnectionId;
            m_nextConnectionId++;

            // If the ADVF_PRIMEFIRST flag is specified and the data exists,
            // raise the DataChanged event now.
            if ((advf & ADVF.ADVF_PRIMEFIRST) == ADVF.ADVF_PRIMEFIRST)
            {
                OleData dataEntry;
                if (GetDataEntry(ref pFormatetc, out dataEntry))
                    RaiseDataChanged(connection, ref dataEntry);
            }

            return 0;
        }
Example #5
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);
        }
Example #6
0
        private static void SetBoolFormat(this IDataObject dataObject, string format, bool val)
        {
            DataFormats.Format dataFormat = DataFormats.GetFormat(format);

            ComTypes.FORMATETC formatETC = new ComTypes.FORMATETC();
            formatETC.cfFormat = (short)dataFormat.Id;
            formatETC.dwAspect = ComTypes.DVASPECT.DVASPECT_CONTENT;
            formatETC.lindex   = -1;
            formatETC.ptd      = IntPtr.Zero;
            formatETC.tymed    = ComTypes.TYMED.TYMED_HGLOBAL;
            IntPtr num = Marshal.AllocHGlobal(4);

            try
            {
                Marshal.Copy(BitConverter.GetBytes(val ? 1 : 0), 0, num, 4);
                ComTypes.STGMEDIUM medium;
                medium.pUnkForRelease = (object)null;
                medium.tymed          = ComTypes.TYMED.TYMED_HGLOBAL;
                medium.unionmember    = num;
                ((System.Runtime.InteropServices.ComTypes.IDataObject)dataObject).SetData(ref formatETC, ref medium, true);
            }
            catch
            {
                Marshal.FreeHGlobal(num);
                throw;
            }
        }
Example #7
0
		/// <summary>
		/// Adds an advisory connection for the specified format.
		/// </summary>
		/// <param name="pFormatetc">The format for which this sink is called for changes.</param>
		/// <param name="advf">Advisory flags to specify callback behavior.</param>
		/// <param name="adviseSink">The IAdviseSink to call for this connection.</param>
		/// <param name="connection">Returns the new connection's ID.</param>
		/// <returns>An HRESULT.</returns>
		public int DAdvise(ref FORMATETC pFormatetc, ADVF advf, IAdviseSink adviseSink, out int connection) {
			// Check that the specified advisory flags are supported.
			const ADVF ADVF_ALLOWED = ADVF.ADVF_NODATA | ADVF.ADVF_ONLYONCE | ADVF.ADVF_PRIMEFIRST;
			if ((int) ((advf | ADVF_ALLOWED) ^ ADVF_ALLOWED) != 0) {
				connection = 0;
				return OLE_E_ADVISENOTSUPPORTED;
			}

			// Create and insert an entry for the connection list
			var entry = new AdviseEntry(ref pFormatetc, advf, adviseSink);
			connections.Add(nextConnectionId, entry);
			connection = nextConnectionId;
			nextConnectionId++;

			// If the ADVF_PRIMEFIRST flag is specified and the data exists,
			// raise the DataChanged event now.
			if ((advf & ADVF.ADVF_PRIMEFIRST) == ADVF.ADVF_PRIMEFIRST) {
				KeyValuePair<FORMATETC, STGMEDIUM> dataEntry;
				if (GetDataEntry(ref pFormatetc, out dataEntry))
					RaiseDataChanged(connection, ref dataEntry);
			}

			// S_OK
			return 0;
		}
Example #8
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);
 }
Example #9
0
        /// <summary>
        /// Sets managed data to a clipboard DataObject.
        /// </summary>
        /// <param name="dataObject">The DataObject to set the data on.</param>
        /// <param name="format">The clipboard format.</param>
        /// <param name="data">The data object.</param>
        /// <remarks>
        /// Because the underlying data store is not storing managed objects, but
        /// unmanaged ones, this function provides intelligent conversion, allowing
        /// you to set unmanaged data into the COM implemented IDataObject.</remarks>
        public static void SetDataEx(this IDataObject dataObject, string format, object data)
        {
            DataFormats.Format dataFormat = DataFormats.GetFormat(format);

            // Initialize the format structure
            ComTypes.FORMATETC formatETC = new ComTypes.FORMATETC();
            formatETC.cfFormat = (short)dataFormat.Id;
            formatETC.dwAspect = ComTypes.DVASPECT.DVASPECT_CONTENT;
            formatETC.lindex   = -1;
            formatETC.ptd      = IntPtr.Zero;

            // Try to discover the TYMED from the format and data
            ComTypes.TYMED tymed = GetCompatibleTymed(format, data);
            // If a TYMED was found, we can use the system DataObject
            // to convert our value for us.
            if (tymed != ComTypes.TYMED.TYMED_NULL)
            {
                formatETC.tymed = tymed;

                if (data is byte[] bytes)
                {
                    // don't convert byte array as it adds extra data
                    ComTypes.ComDataObjectExtensions.SetByteData((ComTypes.IDataObject)dataObject, format, bytes);
                }
                else
                {
                    // Set data on an empty DataObject instance
                    DataObject conv = new DataObject();
                    conv.SetData(format, true, data);

                    // Now retrieve the data, using the COM interface.
                    // This will perform a managed to unmanaged conversion for us.
                    ComTypes.STGMEDIUM medium;
                    ((ComTypes.IDataObject)conv).GetData(ref formatETC, out medium);
                    try
                    {
                        // Now set the data on our data object
                        ((ComTypes.IDataObject)dataObject).SetData(ref formatETC, ref medium, true);
                    }
                    catch
                    {
                        // On exceptions, release the medium
                        ReleaseStgMedium(ref medium);
                        throw;
                    }
                }
            }
            else
            {
                // Since we couldn't determine a TYMED, this data
                // is likely custom managed data, and won't be used
                // by unmanaged code, so we'll use our custom marshaling
                // implemented by our COM IDataObject extensions.

                ComTypes.ComDataObjectExtensions.SetManagedData((ComTypes.IDataObject)dataObject, format, data);
            }
        }
Example #10
0
 ///////////////////////////////////////////////////////////////////////////////////
 // FORMATETC
 static internal OleInterop.FORMATETC BclFormatETC2Ole(ref BclComTypes.FORMATETC bclFormat)
 {
     OleInterop.FORMATETC oleFormat;
     oleFormat.cfFormat = (ushort)bclFormat.cfFormat;
     oleFormat.dwAspect = (uint)bclFormat.dwAspect;
     oleFormat.lindex   = bclFormat.lindex;
     oleFormat.ptd      = bclFormat.ptd;
     oleFormat.tymed    = (uint)bclFormat.tymed;
     return(oleFormat);
 }
        /// <summary>
        /// Extracts data of type <c>Dataformat.Html</c> from an <c>IDataObject</c> data container
        /// This method shouldn't throw any exception but writes relevant exception informations in the debug window
        /// </summary>
        /// <param name="data">data container</param>
        /// <returns>A byte[] array with the decoded string or null if the method fails</returns>
        /// <remarks>Added 2006-06-12, <c>Uwe Keim</c>.</remarks>
        private static byte[] getHtml(
            IDataObject data)
        {
            var interopData = (System.Runtime.InteropServices.ComTypes.IDataObject)data;

            var format =
                new FORMATETC
                {
                    cfFormat = ((short)DataFormats.GetFormat(DataFormats.Html).Id),
                    dwAspect = DVASPECT.DVASPECT_CONTENT,
                    lindex = (-1),
                    tymed = TYMED.TYMED_HGLOBAL
                };

            STGMEDIUM stgmedium;
            stgmedium.tymed = TYMED.TYMED_HGLOBAL;
            stgmedium.pUnkForRelease = null;

            var queryResult = interopData.QueryGetData(ref format);

            if (queryResult != 0)
            {
                return null;
            }

            interopData.GetData(ref format, out stgmedium);

            if (stgmedium.unionmember == IntPtr.Zero)
            {
                return null;
            }

            var pointer = stgmedium.unionmember;

            var handleRef = new HandleRef(null, pointer);

            byte[] rawArray;

            try
            {
                var ptr1 = GlobalLock(handleRef);

                var length = GlobalSize(handleRef);

                rawArray = new byte[length];

                Marshal.Copy(ptr1, rawArray, 0, length);
            }
            finally
            {
                GlobalUnlock(handleRef);
            }

            return rawArray;
        }
Example #12
0
        int BclComTypes.IDataObject.QueryGetData(ref BclComTypes.FORMATETC format)
        {
            if (null != bclData)
            {
                return(bclData.QueryGetData(ref format));
            }

            OleInterop.FORMATETC[] oleFormat = new OleInterop.FORMATETC[1];
            oleFormat[0] = StructConverter.BclFormatETC2Ole(ref format);
            return(oleData.QueryGetData(oleFormat));
        }
Example #13
0
        public int GetCanonicalFormatEtc(ref FORMATETC formatIn, out FORMATETC formatOut)
        {
            switch (formatIn.cfFormat)
            {
            case CF.TEXT:
            case CF.UNICODETEXT:
                return(PlainTextDataObject.GetCanonicalFormatEtc(ref formatIn, out formatOut));

            default:
                return(DataObject.GetCanonicalFormatEtc(ref formatIn, out formatOut));
            }
        }
Example #14
0
        public int QueryGetData(ref FORMATETC format)
        {
            switch (format.cfFormat)
            {
            case CF.TEXT:
            case CF.UNICODETEXT:
                return(PlainTextDataObject.QueryGetData(ref format));

            default:
                return(DataObject.QueryGetData(ref format));
            }
        }
        /// <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;
        }
Example #16
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;
            }
        }
Example #17
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);
        }
Example #18
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);
        }
Example #19
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]);
        }
Example #20
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;
            }
        }
Example #21
0
        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);
              }
        }
Example #22
0
        int OleInterop.IDataObject.QueryGetData(OleInterop.FORMATETC[] pFormatetc)
        {
            if (null != oleData)
            {
                return(oleData.QueryGetData(pFormatetc));
            }

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

            BclComTypes.FORMATETC bclFormat = StructConverter.OleFormatETC2Bcl(ref pFormatetc[0]);
            return(bclData.QueryGetData(ref bclFormat));
        }
Example #23
0
        int BclComTypes.IDataObject.GetCanonicalFormatEtc(ref BclComTypes.FORMATETC formatIn, out BclComTypes.FORMATETC formatOut)
        {
            if (null != bclData)
            {
                return(bclData.GetCanonicalFormatEtc(ref formatIn, out formatOut));
            }

            OleInterop.FORMATETC[] oleFormatIn  = new OleInterop.FORMATETC[1];
            OleInterop.FORMATETC[] oleFormatOut = new OleInterop.FORMATETC[1];
            oleFormatIn[0] = StructConverter.BclFormatETC2Ole(ref formatIn);
            int hr = oleData.GetCanonicalFormatEtc(oleFormatIn, oleFormatOut);

            NativeMethods.ThrowOnFailure(hr);
            formatOut = StructConverter.OleFormatETC2Bcl(ref oleFormatOut[0]);
            return(hr);
        }
Example #24
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);
 }
Example #25
0
        public void Initialize(IntPtr pidlFolder, IntPtr pDataObj, IntPtr hKeyProgID)
        {
            if (pDataObj == IntPtr.Zero)
            {
                throw new ArgumentException();
            }

            FORMATETC fe = new FORMATETC();
            fe.cfFormat = (short)CLIPFORMAT.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();
                }

                uint nFiles = Import.DragQueryFile(hDrop, UInt32.MaxValue, null, 0);
                if (nFiles == 0)
                {
                    Marshal.ThrowExceptionForHR(ErrorCode.E_FAIL);
                }

                selectedFiles = new List<string>();
                for (uint i = 0; i < nFiles; i++)
                {
                    selectedFiles.Add(getFileName(hDrop, i));
                }
            }
            finally
            {
                Import.ReleaseStgMedium(ref stm);
            }
        }
        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());
        }
Example #27
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);
 }
Example #28
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);
        }
Example #29
0
 public int DAdvise(ref FORMATETC formatetc, ADVF advf, IAdviseSink adviseSink, out int connection)
 {
     if (((advf | ADVF.ADVF_NODATA | ADVF.ADVF_PRIMEFIRST | ADVF.ADVF_ONLYONCE) ^ (ADVF.ADVF_NODATA | ADVF.ADVF_PRIMEFIRST | ADVF.ADVF_ONLYONCE)) != (ADVF)0)
     {
         connection = 0;
         return -2147221501;
     }
     else
     {
         this.connections.Add(this.nextConnectionId, new AdviseEntry(ref formatetc, advf, adviseSink));
         connection = this.nextConnectionId;
         ++this.nextConnectionId;
         KeyValuePair<FORMATETC, STGMEDIUM> dataEntry;
         if ((advf & ADVF.ADVF_PRIMEFIRST) == ADVF.ADVF_PRIMEFIRST && this.GetDataEntry(ref formatetc, out dataEntry))
             this.RaiseDataChanged(connection, ref dataEntry);
         return 0;
     }
 }
Example #30
0
        internal static bool IsFormatValid(FORMATETC[] formats) {

            Debug.Assert(formats != null, "Null returned from GetFormats");
            if (formats != null) {
                if (formats.Length <= 4) {
                    for (int i = 0; i < formats.Length; i++) {
                        short format = formats[i].cfFormat;
                        if (format != NativeMethods.CF_TEXT &&
                            format !=  NativeMethods.CF_UNICODETEXT && 
                            format !=  DataFormats.GetFormat("System.String").Id &&
                            format !=  DataFormats.GetFormat("Csv").Id) {
                                return false;
                        }
                    }
                    return true;
                }
            }
            return false;
        }
Example #31
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);
            }
        }
Example #32
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);
        }
Example #33
0
        public static List <byte[][]> GetPidls(System.Runtime.InteropServices.ComTypes.IDataObject pDataObj)
        {
            List <byte[][]> lsRet = new List <byte[][]>();

            try
            {
                STGMEDIUM medium;
                System.Runtime.InteropServices.ComTypes.FORMATETC formatShell = new System.Runtime.InteropServices.ComTypes.FORMATETC()
                {
                    cfFormat = (Int16)DataFormats.GetFormat(NativeMethods.CFSTR_SHELLIDLIST).Id,
                    dwAspect = DVASPECT.DVASPECT_CONTENT,
                    tymed    = TYMED.TYMED_HGLOBAL
                };
                System.Runtime.InteropServices.ComTypes.FORMATETC format = new System.Runtime.InteropServices.ComTypes.FORMATETC()
                {
                    cfFormat = (Int16)DataFormats.GetFormat(NativeMethods.CF_HDROP).Id,
                    dwAspect = DVASPECT.DVASPECT_CONTENT,
                    tymed    = TYMED.TYMED_HGLOBAL
                };
                int ret = pDataObj.QueryGetData(ref format);
                if (ret > 0)
                {
                    pDataObj.GetData(ref formatShell, out medium);

                    IntPtr ptr;
                    ptr = medium.unionmember;

                    IntPtr ptrLock = NativeMethods.GlobalLock(ptr);

                    lsRet = ProcessCIDA_Pidl(ptr);

                    NativeMethods.GlobalUnlock(ptrLock);
                }
            }
            catch (Exception)
            {
            }

            return(lsRet);
        }
Example #34
0
        public void Drop(IDataObject dataObject, uint keyState, Point pt, ref uint effect)
        {
            FORMATETC format = new FORMATETC()
            {
                cfFormat = NativeMethods.CF_HDROP,
                dwAspect = DVASPECT.DVASPECT_CONTENT,
                tymed = TYMED.TYMED_HGLOBAL
            };
            STGMEDIUM medium;
            string[] files;
            dataObject.GetData(ref format, out medium);
            try
            {
                IntPtr dropHandle = medium.unionmember;
                int fileCount = NativeMethods.DragQueryFile(new HandleRef(this, dropHandle), -1, null, 0);
                files = new string[fileCount];
                for (int x = 0; x < fileCount; ++x)
                {
                    int size = NativeMethods.DragQueryFile(new HandleRef(this, dropHandle), x, null, 0);
                    if (size > 0)
                    {
                        StringBuilder fileName = new StringBuilder(size + 1);
                        if (NativeMethods.DragQueryFile(new HandleRef(this, dropHandle), x, fileName, fileName.Capacity) > 0)
                            files[x] = fileName.ToString();
                    }
                }
            }
            finally
            {
                NativeMethods.ReleaseStgMedium(ref medium);
            }

            foreach (string file in files)
            {
                Client.OpenGLContextThread.Add(() => 
                {
                    ImportExportUtil.Import(file);
                });
            }
        }
Example #35
0
        int OleInterop.IDataObject.GetCanonicalFormatEtc(OleInterop.FORMATETC[] pformatectIn, OleInterop.FORMATETC[] pformatetcOut)
        {
            if (null != oleData)
            {
                return(oleData.GetCanonicalFormatEtc(pformatectIn, pformatetcOut));
            }

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

            BclComTypes.FORMATETC bclFormatIn = StructConverter.OleFormatETC2Bcl(ref pformatectIn[0]);
            BclComTypes.FORMATETC bclFormatOut;
            int hr = bclData.GetCanonicalFormatEtc(ref bclFormatIn, out bclFormatOut);

            NativeMethods.ThrowOnFailure(hr);
            pformatetcOut[0] = StructConverter.BclFormatETC2Ole(ref bclFormatOut);
            return(hr);
        }
Example #36
0
        int BclComTypes.IDataObject.DAdvise(ref BclComTypes.FORMATETC pFormatetc, BclComTypes.ADVF advf, BclComTypes.IAdviseSink adviseSink, out int connection)
        {
            if (null != bclData)
            {
                return(bclData.DAdvise(ref pFormatetc, advf, adviseSink, out connection));
            }

            OleInterop.FORMATETC[] oleFormat = new OleInterop.FORMATETC[1];
            oleFormat[0] = StructConverter.BclFormatETC2Ole(ref pFormatetc);
            uint result;

            OleInterop.IAdviseSink oleSink = adviseSink as OleInterop.IAdviseSink;
            if (null == oleSink)
            {
                oleSink = (OleInterop.IAdviseSink)(new AdviseSink(adviseSink));
            }
            int hr = oleData.DAdvise(oleFormat, (uint)advf, oleSink, out result);

            NativeMethods.ThrowOnFailure(hr);
            connection = (int)result;
            return(hr);
        }
Example #37
0
        //[SecurityPermission(SecurityAction.Demand, Flags = SecurityPermissionFlag.UnmanagedCode)]
        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(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);
            }
        }
Example #38
0
        public static void SetDataEx(this System.Windows.IDataObject dataObject, string format, object data)
        {
            DataFormat dataFormat = DataFormats.GetDataFormat(format);
            FORMATETC formatetc = new FORMATETC()
            {
                cfFormat = (short)dataFormat.Id,
                dwAspect = DVASPECT.DVASPECT_CONTENT,
                lindex = -1,
                ptd = IntPtr.Zero
            };
            TYMED compatibleTymed = DataObjectExtensions.GetCompatibleTymed(format, data);
            if (compatibleTymed != TYMED.TYMED_NULL)
            {
                formatetc.tymed = compatibleTymed;
                System.Windows.IDataObject dataObject1 = new System.Windows.DataObject();

                dataObject1.SetData(format, data, true);

                STGMEDIUM medium;

                ((System.Runtime.InteropServices.ComTypes.IDataObject)dataObject1).GetData(ref formatetc, out medium);

                try
                {
                    ((System.Runtime.InteropServices.ComTypes.IDataObject)dataObject).SetData(ref formatetc, ref medium, true);
                }
                catch
                {
                    Advent.Common.Interop.NativeMethods.ReleaseStgMedium(ref medium);
                    throw;
                }
            }
            else
                DataObjectExtensions.SetManagedData(dataObject, format, data);
        }
Example #39
0
 public static void SetVirtualFiles(this Advent.Common.Interop.DataObject dataObject, VirtualFile[] files)
 {
     MemoryStream memoryStream = new MemoryStream();
     memoryStream.Write(BitConverter.GetBytes(files.Length), 0, 4);
     for (int index = 0; index < files.Length; ++index)
     {
         VirtualFile file = files[index];
         if (file.ContentsFunc == null)
         {
             FORMATETC formatIn = new FORMATETC()
             {
                 cfFormat = (short)DataFormats.GetDataFormat("FileContents").Id,
                 dwAspect = DVASPECT.DVASPECT_CONTENT,
                 lindex = index,
                 ptd = IntPtr.Zero,
                 tymed = TYMED.TYMED_ISTREAM
             };
             STGMEDIUM medium = DataObjectExtensions.WriteBytesToMedium(file.Contents);
             dataObject.SetData(ref formatIn, ref medium, true);
         }
         DataObjectExtensions.WriteFileDescriptor((Stream)memoryStream, file);
     }
     dataObject.DataRequested += (EventHandler<DataRequestedEventArgs>)((sender, args) =>
     {
         int local_0 = (int)(short)DataFormats.GetDataFormat("FileContents").Id;
         if ((int)args.Format.cfFormat != local_0 || args.Format.lindex < 0 || (args.Format.lindex >= files.Length || files[args.Format.lindex].ContentsFunc == null))
             return;
         args.Medium = DataObjectExtensions.WriteBytesToMedium(files[args.Format.lindex].ContentsFunc());
         args.IsHandled = true;
     });
     IntPtr num = Marshal.AllocHGlobal((int)memoryStream.Length);
     try
     {
         Marshal.Copy(memoryStream.GetBuffer(), 0, num, (int)memoryStream.Length);
     }
     catch
     {
         Marshal.FreeHGlobal(num);
         throw;
     }
     STGMEDIUM medium1;
     medium1.pUnkForRelease = (object)null;
     medium1.tymed = TYMED.TYMED_HGLOBAL;
     medium1.unionmember = num;
     FORMATETC formatIn1 = new FORMATETC()
     {
         cfFormat = (short)DataFormats.GetDataFormat("FileGroupDescriptorW").Id,
         dwAspect = DVASPECT.DVASPECT_CONTENT,
         lindex = -1,
         ptd = IntPtr.Zero,
         tymed = TYMED.TYMED_HGLOBAL
     };
     dataObject.SetData(ref formatIn1, ref medium1, true);
 }
Example #40
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();
        }
Example #41
0
 public void OnDataChange(ref FORMATETC format, ref STGMEDIUM stgmedium)
 {
     if (DataObjectExtensions.GetDropDescription(this.data) == null)
         return;
     DataObjectExtensions.SetDropDescriptionIsDefault(this.data, false);
 }
Example #42
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);
Example #43
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;
            }
Example #44
0
 int IComDataObject.GetCanonicalFormatEtc(ref FORMATETC pformatetcIn, out FORMATETC pformatetcOut) {
     Debug.WriteLineIf(CompModSwitches.DataObject.TraceVerbose, "GetCanonicalFormatEtc");
     if (innerData is OleConverter) {
         return ((OleConverter)innerData).OleDataObject.GetCanonicalFormatEtc(ref pformatetcIn, out pformatetcOut);
     }
     pformatetcOut = new FORMATETC();
     return (DATA_S_SAMEFORMATETC);
 }
Example #45
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 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);
     }
 }
Example #46
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);
            }
        }
Example #47
0
 int IComDataObject.DAdvise(ref FORMATETC pFormatetc, ADVF advf, IAdviseSink pAdvSink, out int pdwConnection) {
     Debug.WriteLineIf(CompModSwitches.DataObject.TraceVerbose, "DAdvise");
     if (innerData is OleConverter) {
         return ((OleConverter)innerData).OleDataObject.DAdvise(ref pFormatetc, advf, pAdvSink, out pdwConnection);
     }
     pdwConnection = 0;
     return (NativeMethods.E_NOTIMPL);
 }
Example #48
0
            public virtual string[] GetFormats(bool autoConvert) {
                Debug.Assert(innerData != null, "You must have an innerData on all DataObjects");

                IEnumFORMATETC enumFORMATETC = null;
                ArrayList formats = new ArrayList();
                try {
                    enumFORMATETC = innerData.EnumFormatEtc(DATADIR.DATADIR_GET);
                }
                catch {
                }

                if (enumFORMATETC != null) {
                    enumFORMATETC.Reset();

                    FORMATETC[] formatetc = new FORMATETC[] { new FORMATETC()};
                    int[] retrieved = new int[] {1};

                    while (retrieved[0] > 0) {
                        retrieved[0] = 0;
                        try {
                            enumFORMATETC.Next(1, formatetc, retrieved);
                        }
                        catch {
                        }

                        if (retrieved[0] > 0) {
                            string name = DataFormats.GetFormat(formatetc[0].cfFormat).Name;
                            if (autoConvert) {
                                string[] mappedFormats = GetMappedFormats(name);
                                for (int i=0; i<mappedFormats.Length; i++) {
                                    formats.Add(mappedFormats[i]);
                                }
                            }
                            else {
                                formats.Add(name);
                            }
                        }
                    }
                }

                string[] temp = new string[formats.Count];
                formats.CopyTo(temp, 0);
                return GetDistinctStrings(temp);
            }
Example #49
0
            private bool GetDataPresentInner(string format) {
                Debug.Assert(innerData != null, "You must have an innerData on all DataObjects");
                FORMATETC formatetc = new FORMATETC();
                formatetc.cfFormat = unchecked((short)(ushort)(DataFormats.GetFormat(format).Id));
                formatetc.dwAspect = DVASPECT.DVASPECT_CONTENT;
                formatetc.lindex = -1;

                for (int i=0; i<ALLOWED_TYMEDS.Length; i++) {
                    formatetc.tymed |= ALLOWED_TYMEDS[i];
                }

                int hr = QueryGetDataUnsafe(ref formatetc);
                return (hr == NativeMethods.S_OK);
            }
Example #50
0
 private int QueryGetDataInner(ref FORMATETC formatetc)
 {
     return innerData.QueryGetData(ref formatetc);
 }
Example #51
0
 public static void SetVirtualFiles(this System.Windows.IDataObject dataObject, VirtualFile[] files)
 {
     if (files == null)
         throw new ArgumentNullException();
     MemoryStream memoryStream = new MemoryStream();
     memoryStream.Write(BitConverter.GetBytes(files.Length), 0, 4);
     for (int index = 0; index < files.Length; ++index)
     {
         VirtualFile file = files[index];
         if (file.Contents == null || file.Contents.Length == 0)
             throw new ArgumentException("VirtualFile does not have any contents.");
         FORMATETC formatIn = new FORMATETC()
         {
             cfFormat = (short)DataFormats.GetDataFormat("FileContents").Id,
             dwAspect = DVASPECT.DVASPECT_CONTENT,
             lindex = index,
             ptd = IntPtr.Zero,
             tymed = TYMED.TYMED_ISTREAM
         };
         STGMEDIUM medium = DataObjectExtensions.WriteBytesToMedium(file.Contents);
         ((System.Runtime.InteropServices.ComTypes.IDataObject)dataObject).SetData(ref formatIn, ref medium, true);
         DataObjectExtensions.WriteFileDescriptor((Stream)memoryStream, file);
     }
     IntPtr num = Marshal.AllocHGlobal((int)memoryStream.Length);
     try
     {
         Marshal.Copy(memoryStream.GetBuffer(), 0, num, (int)memoryStream.Length);
     }
     catch
     {
         Marshal.FreeHGlobal(num);
         throw;
     }
     STGMEDIUM medium1;
     medium1.pUnkForRelease = (object)null;
     medium1.tymed = TYMED.TYMED_HGLOBAL;
     medium1.unionmember = num;
     FORMATETC formatIn1 = new FORMATETC()
     {
         cfFormat = (short)DataFormats.GetDataFormat("FileGroupDescriptorW").Id,
         dwAspect = DVASPECT.DVASPECT_CONTENT,
         lindex = -1,
         ptd = IntPtr.Zero,
         tymed = TYMED.TYMED_HGLOBAL
     };
     ((System.Runtime.InteropServices.ComTypes.IDataObject)dataObject).SetData(ref formatIn1, ref medium1, true);
 }
Example #52
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);
            }
        }
Example #53
0
 private static void FillFormatETC(string format, TYMED tymed, out FORMATETC formatETC)
 {
     formatETC.cfFormat = (short)Advent.Common.Interop.NativeMethods.RegisterClipboardFormat(format);
     formatETC.dwAspect = DVASPECT.DVASPECT_CONTENT;
     formatETC.lindex = -1;
     formatETC.ptd = IntPtr.Zero;
     formatETC.tymed = tymed;
 }
Example #54
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);
     }
 }
Example #55
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);
            }
        }
Example #56
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 NativeMethods.S_FALSE;
                    }
                    else {
                        if (!GetDataPresent(DataFormats.GetFormat(formatetc.cfFormat).Name)) {
                            return (DV_E_FORMATETC);
                        }
                    }
                }
                else {
                    return (DV_E_TYMED);
                }
            }
            else {
                return (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 NativeMethods.S_OK;
        }
Example #57
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);
            }
        }
 internal static bool IsFormatValid(FORMATETC[] formats)
 {
     if ((formats == null) || (formats.Length > 4))
     {
         return false;
     }
     for (int i = 0; i < formats.Length; i++)
     {
         short cfFormat = formats[i].cfFormat;
         if (((cfFormat != 1) && (cfFormat != 13)) && ((cfFormat != DataFormats.GetFormat("System.String").Id) && (cfFormat != DataFormats.GetFormat("Csv").Id)))
         {
             return false;
         }
     }
     return true;
 }
        // ------------------------------------------------------------------
        /// <summary>
        /// Extracts data of type <c>Dataformat.Html</c> from an <c>IDataObject</c> data container
        /// This method shouldn't throw any exception but writes relevant exception informations in the debug window
        /// </summary>
        /// <param name="data">data container</param>
        /// <returns>A byte[] array with the decoded string or null if the method fails</returns>
        /// <remarks>Added 2006-06-12, <c>Uwe Keim</c>.</remarks>
        private static byte[] getHtml(
            System.Windows.Forms.IDataObject data)
        {
            var interopData = (System.Runtime.InteropServices.ComTypes.IDataObject)data;

            var format =
                new FORMATETC
                {
                    cfFormat = ((short)DataFormats.GetFormat(DataFormats.Html).Id),
                    dwAspect = DVASPECT.DVASPECT_CONTENT,
                    lindex = (-1),
                    tymed = TYMED.TYMED_HGLOBAL
                };

            STGMEDIUM stgmedium;
            stgmedium.tymed = TYMED.TYMED_HGLOBAL;
            stgmedium.pUnkForRelease = null;

            //try
            //{
            var queryResult = interopData.QueryGetData(ref format);
            //}
            //catch ( Exception exp )
            //{
            //	Debug.WriteLine( "HtmlFromIDataObject.GetHtml -> QueryGetData(ref format) threw an exception: "
            //		+ Environment.NewLine + exp.ToString() );
            //	return null;
            //}

            if (queryResult != 0)
            {
                //Debug.WriteLine(
                //    string.Format(
                //        @"HtmlFromIDataObject.GetHtml -> QueryGetData(ref format) returned a code != 0 code: {0}",
                //        queryResult));
                return null;
            }

            //try
            //{
            interopData.GetData(ref format, out stgmedium);
            //}
            //catch ( Exception exp )
            //{
            //	System.Diagnostics.Debug.WriteLine( "HtmlFromIDataObject.GetHtml -> GetData(ref format, out stgmedium) threw this exception: "
            //		+ Environment.NewLine + exp.ToString() );
            //	return null;
            //}

            if (stgmedium.unionmember == IntPtr.Zero)
            {
                //Debug.WriteLine(
                //    @"HtmlFromIDataObject.GetHtml -> stgmedium.unionmember returned an IntPtr pointing to zero");
                return null;
            }

            var pointer = stgmedium.unionmember;

            var handleRef = new HandleRef(null, pointer);

            byte[] rawArray;

            try
            {
                var ptr1 = GlobalLock(handleRef);

                var length = GlobalSize(handleRef);

                rawArray = new byte[length];

                Marshal.Copy(ptr1, rawArray, 0, length);
            }
            //catch ( Exception exp )
            //{
            //	Debug.WriteLine( "HtmlFromIDataObject.GetHtml -> Html Import threw an exception: " + Environment.NewLine + exp.ToString() );
            //}
            finally
            {
                GlobalUnlock(handleRef);
            }

            return rawArray;
        }
Example #60
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;
            }