Esempio n. 1
0
            public static FILEDESCRIPTOR[] GetFileDescriptors(System.Runtime.InteropServices.ComTypes.IDataObject DataObject, out IntPtr hGlobal)
            {
                FORMATETC _req = new FORMATETC();

                _req.tymed    = TYMED.TYMED_HGLOBAL;
                _req.dwAspect = DVASPECT.DVASPECT_CONTENT;
                _req.cfFormat = (short)(System.Windows.DataFormats.GetDataFormat("FileGroupDescriptorW").Id);
                _req.lindex   = -1;

                STGMEDIUM _val;

                DataObject.GetData(_req, out _val);

                hGlobal = _val.unionmember;
                IntPtr _fgptr = GlobalLock(_val.unionmember);

                NativeMethods.FILEGROUPDESCRIPTOR _fg;

                _fg = (NativeMethods.FILEGROUPDESCRIPTOR)Marshal.PtrToStructure(_fgptr, typeof(NativeMethods.FILEGROUPDESCRIPTOR));

                _fgptr = new IntPtr(_fgptr.ToInt64() + 4);

                NativeMethods.FILEDESCRIPTOR[] _fileDesc = new NativeMethods.FILEDESCRIPTOR[_fg.cItems];

                for (int _i = 0; _i < _fg.cItems; _i++)
                {
                    _fileDesc[_i] = (NativeMethods.FILEDESCRIPTOR)Marshal.PtrToStructure(_fgptr, typeof(NativeMethods.FILEDESCRIPTOR));

                    _fgptr = new IntPtr(_fgptr.ToInt64() + Marshal.SizeOf(typeof(NativeMethods.FILEDESCRIPTOR)));
                }

                return(_fileDesc);
            }
        public static object GetDropDescription(this System.Runtime.InteropServices.ComTypes.IDataObject dataObject)
        {
            FORMATETC formatETC;

            FillFormatETC(DropDescriptionFormat, TYMED.TYMED_HGLOBAL, out formatETC);

            if (0 == dataObject.QueryGetData(ref formatETC))
            {
                STGMEDIUM medium;
                dataObject.GetData(ref formatETC, out medium);
                try
                {
                    return((DataObject.DropDescription)Marshal.PtrToStructure(medium.unionmember, typeof(BExplorer.Shell.DataObject.DropDescription)));
                }
                catch (AccessViolationException)
                {
                }
                finally
                {
                    ReleaseStgMedium(ref medium);
                }
            }

            return(null);
        }
        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;

            // 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);
                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);
                    }
                    _selectedFile = fileName.ToString();
                    if (!AcceptFile(_selectedFile))
                    {
                        Marshal.ThrowExceptionForHR(WinError.E_FAIL);
                    }
                }
                else
                {
                    Marshal.ThrowExceptionForHR(WinError.E_FAIL);
                }
            }
            finally
            {
                NativeMethods.ReleaseStgMedium(ref stm);
            }
        }
Esempio n. 4
0
            private unsafe object GetDataFromOleIStream(string format)
            {
                FORMATETC formatetc = new FORMATETC();
                STGMEDIUM medium    = new STGMEDIUM();

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

                medium.tymed = TYMED.TYMED_ISTREAM;

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

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

                if (medium.unionmember != IntPtr.Zero)
                {
                    Ole32.IStream pStream = (Ole32.IStream)Marshal.GetObjectForIUnknown(medium.unionmember);
                    Marshal.Release(medium.unionmember);
                    pStream.Stat(out Ole32.STATSTG sstg, Ole32.STATFLAG.STATFLAG_DEFAULT);

                    IntPtr hglobal = Kernel32.GlobalAlloc(
                        Kernel32.GMEM.MOVEABLE | Kernel32.GMEM.DDESHARE | Kernel32.GMEM.ZEROINIT,
                        (uint)sstg.cbSize);
                    IntPtr ptr = Kernel32.GlobalLock(hglobal);
                    pStream.Read((byte *)ptr, (uint)sstg.cbSize, null);
                    Kernel32.GlobalUnlock(hglobal);

                    return(GetDataFromHGLOBAL(format, hglobal));
                }

                return(null);
            }
Esempio n. 5
0
        private DirectoryObject[] ProcessSelections(System.Runtime.InteropServices.ComTypes.IDataObject dataObj)
        {
            const string ClipboardFormat = "CFSTR_DSOP_DS_SELECTION_LIST";

            if (dataObj == null)
            {
                return(null);
            }

            DirectoryObject[] result = null;
            STGMEDIUM         stg;
            var fe = new FORMATETC
            {
                cfFormat = (short)DataFormats.GetFormat(ClipboardFormat).Id,
                ptd      = IntPtr.Zero,
                dwAspect = DVASPECT.DVASPECT_CONTENT,
                lindex   = -1,
                tymed    = TYMED.TYMED_HGLOBAL
            };

            dataObj.GetData(ref fe, out stg);

            var dsSelectionList = Memory.NativeMethods.GlobalLock(stg.unionmember);

            if (dsSelectionList == IntPtr.Zero)
            {
                NativeMethods.ReportWin32Exception();
            }

            try {
                var current = dsSelectionList;
                var count   = Marshal.ReadInt32(current);
                var fetchedAttributesCount = Marshal.ReadInt32(current, Marshal.SizeOf(typeof(uint)));

                if (count > 0)
                {
                    result   = new DirectoryObject[count];
                    current += Marshal.SizeOf(typeof(uint)) * 2;

                    for (var i = 0; i < count; i++)
                    {
                        var selection = (DSSelection)Marshal.PtrToStructure(current, typeof(DSSelection));
                        result[i] = new DirectoryObject(selection.pwzName, selection.pwzADsPath, selection.pwzClass, selection.pwzUPN,
                                                        GetFetchedAttributes(selection.pvarFetchedAttributes, fetchedAttributesCount, selection.pwzClass));

                        current += Marshal.SizeOf(typeof(DSSelection));
                    }
                }
            }
            finally {
                Memory.NativeMethods.GlobalUnlock(dsSelectionList);
                COM.NativeMethods.ReleaseStgMedium(ref stg);
            }

            return(result);
        }
Esempio n. 6
0
        void OleInterop.IDataObject.GetData(OleInterop.FORMATETC[] pformatetcIn, OleInterop.STGMEDIUM[] pRemoteMedium)
        {
            if (null != oleData)
            {
                oleData.GetData(pformatetcIn, pRemoteMedium);
                return;
            }

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

            // Call the method on the BCL interface
            BclComTypes.FORMATETC bclFormat = StructConverter.OleFormatETC2Bcl(ref pformatetcIn[0]);
            BclComTypes.STGMEDIUM bclMedium;
            bclData.GetData(ref bclFormat, out bclMedium);
            pRemoteMedium[0] = StructConverter.BclSTGMEDIUM2Ole(ref bclMedium);
        }
Esempio n. 7
0
        // ReSharper disable once UnusedMember.Local
        private ShellItem[] ParseShellIdListArray(IDataObject pDataObj)
        {
            var result = new List <ShellItem>();
            var format = new FORMATETC();
            // ReSharper disable once RedundantAssignment
            var medium = new STGMEDIUM();

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

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

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

                for (var n = 0; n <= count; ++n)
                {
                    var pidlOffset  = Marshal.ReadInt32(medium.unionmember, offset);
                    var 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());
        }
        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());
        }
Esempio n. 9
0
 private void GetDataInner(ref FORMATETC format, out STGMEDIUM medium)
 {
     SecurityHelper.DemandUnmanagedCode();
     new SecurityPermission(SecurityPermissionFlag.UnmanagedCode).Assert(); // BlessedAssert
     try
     {
         _oleDataObject.GetData(ref format, out medium);
     }
     catch (Exception exception)
     {
         Logger.Instance.Error(exception);
         medium = default(STGMEDIUM);
     }
     finally
     {
         CodeAccessPermission.RevertAssert();
     }
 }
Esempio n. 10
0
        public int DragEnter(System.Runtime.InteropServices.ComTypes.IDataObject pDataObj, int grfKeyState, BandObjectLib.POINT pt, ref DragDropEffects pdwEffect)
        {
            try {
                if (this.DragFileEnter != null)
                {
                    FORMATETC format = new FORMATETC();
                    format.cfFormat = 15;
                    format.ptd      = IntPtr.Zero;
                    format.dwAspect = DVASPECT.DVASPECT_CONTENT;
                    format.lindex   = -1;
                    format.tymed    = TYMED.TYMED_HGLOBAL;
                    if (pDataObj.QueryGetData(ref format) >= 0)
                    {
                        STGMEDIUM medium = new STGMEDIUM();
                        try {
                            try {
                                pDataObj.GetData(ref format, out medium);
                                pdwEffect = this.DragFileEnter(medium.unionmember, pt, grfKeyState);
                            }
                            catch {
                                pdwEffect = DragDropEffects.None;
                            }
                            goto Label_00A0;
                        }
                        finally {
                            PInvoke.ReleaseStgMedium(ref medium);
                        }
                    }
                    pdwEffect = DragDropEffects.None;
                }
                else
                {
                    pdwEffect = DragDropEffects.Copy;
                }
            }
            finally {
                if (pDataObj != null)
                {
                    Marshal.FinalReleaseComObject(pDataObj);
                }
            }
Label_00A0:
            return(0);
        }
Esempio n. 11
0
        private static Stream ReadFromDataObject(DataObject dataObject, int fileIndex)
        {
            var formatetc = new FORMATETC
            {
                cfFormat = (short)DataFormats.GetDataFormat(NativeMethods.CFSTR_FILECONTENTS).Id,
                dwAspect = DVASPECT.DVASPECT_CONTENT,
                lindex   = fileIndex,
                ptd      = new IntPtr(0),
                tymed    = TYMED.TYMED_ISTREAM
            };

            STGMEDIUM medium;

            System.Runtime.InteropServices.ComTypes.IDataObject obj2 = dataObject;
            obj2.GetData(ref formatetc, out medium);

            try
            {
                if (medium.tymed == TYMED.TYMED_ISTREAM)
                {
                    var mediumStream = (IStream)Marshal.GetTypedObjectForIUnknown(medium.unionmember, typeof(IStream));
                    Marshal.Release(medium.unionmember);

                    var streaWrapper = new ComStreamWrapper(mediumStream, FileAccess.Read, ComRelease.None);

                    streaWrapper.Closed += delegate(object sender, EventArgs e)
                    {
                        NativeMethods.ReleaseStgMedium(ref medium);
                        Marshal.FinalReleaseComObject(mediumStream);
                    };

                    return(streaWrapper);
                }

                throw new NotSupportedException(string.Format("Unsupported STGMEDIUM.tymed ({0})", medium.tymed));
            }
            catch
            {
                NativeMethods.ReleaseStgMedium(ref medium);
                throw;
            }
        }
Esempio n. 12
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);
        }
Esempio n. 13
0
        public int DragDrop(IDataObject pDataObj, int grfKeyState, Point pt, ref DragDropEffects pdwEffect)
        {
            try {
                if(DragFileOver != null) {
                    DragEventArgs e = new DragEventArgs(null, grfKeyState, pt.X, pt.Y, DragDropEffects.Move | DragDropEffects.Copy | DragDropEffects.Scroll, pdwEffect);
                    DragFileOver(null, e);
                    pdwEffect = e.Effect;
                }
                else {
                    pdwEffect = DragDropEffects.Copy;
                }
                if(pdwEffect != DragDropEffects.None) {
                    if(DragFileDrop != null) {
                        IntPtr ptr;
                        byte[] buffer;
                        switch(DragFileDrop(out ptr, out buffer)) {
                            case -1:
                                return 0;

                            case 0: {
                                    IShellFolder ppv = null;
                                    object obj2 = null;
                                    Guid riid = ExplorerGUIDs.IID_IShellFolder;
                                    Guid guid2 = ExplorerGUIDs.IID_IDropTarget;
                                    using(IDLWrapper wrapper = new IDLWrapper(buffer)) {
                                        if(wrapper.Available && wrapper.IsDropTarget) {
                                            try {
                                                IntPtr ptr2;
                                                if(PInvoke.SHBindToParent(wrapper.PIDL, riid, out ppv, out ptr2) == 0) {
                                                    uint rgfReserved = 0;
                                                    IntPtr[] apidl = new IntPtr[] { ptr2 };
                                                    if(ppv.GetUIObjectOf(ptr, 1, apidl, ref guid2, ref rgfReserved, out obj2) == 0) {
                                                        _IDropTarget target = obj2 as _IDropTarget;
                                                        if(target != null) {
                                                            DragDropEffects effects = pdwEffect;
                                                            if(target.DragEnter(pDataObj, iLastKeyState, pt, ref effects) == 0) {
                                                                effects = pdwEffect;
                                                                if(target.DragOver(iLastKeyState, pt, ref effects) == 0) {
                                                                    if((iLastKeyState & 2) != 0) {
                                                                        pdwEffect = DragDropEffects.Link | DragDropEffects.Move | DragDropEffects.Copy;
                                                                    }
                                                                    return target.DragDrop(pDataObj, iLastKeyState, pt, ref pdwEffect);
                                                                }
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                            catch {
                                            }
                                            finally {
                                                if(ppv != null) {
                                                    Marshal.ReleaseComObject(ppv);
                                                }
                                                if(obj2 != null) {
                                                    Marshal.ReleaseComObject(obj2);
                                                }
                                                if(DragDropEnd != null) {
                                                    DragDropEnd(this, EventArgs.Empty);
                                                }
                                            }
                                        }
                                    }
                                    return 0;
                                }
                        }
                    }
                    FORMATETC format = new FORMATETC();
                    format.cfFormat = 15;
                    format.ptd = IntPtr.Zero;
                    format.dwAspect = DVASPECT.DVASPECT_CONTENT;
                    format.lindex = -1;
                    format.tymed = TYMED.TYMED_HGLOBAL;
                    STGMEDIUM medium = new STGMEDIUM();
                    try {
                        pDataObj.GetData(ref format, out medium);
                        PInvoke.SendMessage(hwnd, 0x233, medium.unionmember, IntPtr.Zero);
                    }
                    catch {
                    }
                    finally {
                        PInvoke.ReleaseStgMedium(ref medium);
                    }
                }
            }
            finally {
                if(pDataObj != null) {
                    Marshal.FinalReleaseComObject(pDataObj);
                }
            }
            return 0;
        }
Esempio n. 14
0
            public static byte[] GetFileContents(System.Runtime.InteropServices.ComTypes.IDataObject DataObject, int Index, uint Size)
            {
                byte[] _contents = null;

                FORMATETC _req = new FORMATETC();

                _req.tymed    = TYMED.TYMED_HGLOBAL | TYMED.TYMED_ISTREAM;
                _req.dwAspect = DVASPECT.DVASPECT_CONTENT;
                _req.cfFormat = (short)(System.Windows.DataFormats.GetDataFormat("FileContents").Id);
                _req.lindex   = Index;

                STGMEDIUM _val = new STGMEDIUM();

                DataObject.GetData(_req, out _val);

                switch (_val.tymed)
                {
                case TYMED.TYMED_ISTREAM:
                    IStream _stream = (IStream)Marshal.GetObjectForIUnknown(_val.unionmember);

                    MemoryStream _newStream    = new MemoryStream();
                    IntPtr       _bytesReadPtr = Marshal.AllocHGlobal(8);
                    int          _bytesRead    = 0;

                    try
                    {
                        _stream.Seek(0, 0, _bytesReadPtr);
                    }
                    catch
                    {
                        // Maybe we're already at the start of the stream and it doesn't support Seek.
                    }

                    do
                    {
                        byte[] _buffer = new byte[4096];     // Not reading the whole file at once. We wanna be nice to the IStream.

                        _stream.Read(_buffer, _buffer.Length, _bytesReadPtr);

                        _bytesRead = (int)Marshal.PtrToStructure(_bytesReadPtr, typeof(int));

                        if (_bytesRead > 0)
                        {
                            _newStream.Write(_buffer, 0, _bytesRead);
                        }
                    } while (_bytesRead > 0);

                    _contents = _newStream.ToArray();

                    Marshal.FreeHGlobal(_bytesReadPtr);
                    break;

                case TYMED.TYMED_HGLOBAL:
                    IntPtr _hGlobal = GlobalLock((IntPtr)_val.unionmember);

                    if (_hGlobal == IntPtr.Zero)
                    {
                        _contents = null;
                    }
                    else
                    {
                        try
                        {
                            Marshal.Copy(_hGlobal, _contents, 0, (int)Size);
                        }
                        finally
                        {
                            GlobalUnlock(_hGlobal);
                        }
                    }

                    Marshal.FreeHGlobal((IntPtr)_val.pUnkForRelease);
                    break;

                default:
                    _contents = null;
                    break;
                }

                return(_contents);
            }
Esempio n. 15
0
        /// <summary>
        /// Retrieves the data associated with the specified data format at the specified index.
        /// </summary>
        /// <param name="data">data container to be examined</param>
        /// <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 static MemoryStream GetData(System.Windows.Forms.IDataObject data, string format, int index)
        {
            //create a FORMATETC struct to request the data with
            FORMATETC formatetc = new FORMATETC();

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

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

            //using the Com IDataObject interface get the data using the defined FORMATETC
            System.Runtime.InteropServices.ComTypes.IDataObject d = (System.Runtime.InteropServices.ComTypes.IDataObject)data;
            d.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:
                FieldInfo innerDataField = data.GetType().GetField("innerData", BindingFlags.NonPublic | BindingFlags.Instance);
                object    innerData      = innerDataField.GetValue(data);

                MethodInfo GetDataFromHGLOBAL = innerData.GetType().GetMethod("GetDataFromHGLOBAL", BindingFlags.NonPublic | BindingFlags.Instance);
                object     hGlobalData        = GetDataFromHGLOBAL.Invoke(innerData, new object[] { format, medium.unionmember });
                return((MemoryStream)hGlobalData);
            }

            return(null);
        }
Esempio n. 16
0
            long MsHtmHstInterop.IDropTarget.Drop(
                [In] System.Runtime.InteropServices.ComTypes.IDataObject pDataObject,
                [In] int grfKeyState,
                [In] POINTL pt,
                [In, Out] ref uint pdwEffect
                )
            {
                System.Runtime.InteropServices.ComTypes.IEnumFORMATETC pEnum = (System.Runtime.InteropServices.ComTypes.IEnumFORMATETC)pDataObject.EnumFormatEtc(DATADIR.DATADIR_GET);
                pEnum.Reset();
                FORMATETC[] etcs         = new FORMATETC[1];
                int[]       pceltFetched = new int[1];
                while (pEnum.Next(1, etcs, pceltFetched) == 0)
                {
                    if (etcs[0].cfFormat == 15)
                    {
                        STGMEDIUM data;
                        pDataObject.GetData(ref etcs[0], out data);
                        if (data.tymed == TYMED.TYMED_HGLOBAL)
                        {
                            string[] items = null;
                            IntPtr   pData = GlobalLock(data.unionmember);
                            try
                            {
                                int size = (int)GlobalSize(data.unionmember);
                                int len  = 0;
                                unsafe
                                {
                                    Int32 *pOffset    = (Int32 *)pData;
                                    Int16 *pFileNames = (Int16 *)((Int32)pData + (*pOffset));
                                    size -= *pOffset;
                                    while (true)
                                    {
                                        if (len >= size || (pFileNames[len] == 0 && pFileNames[len + 1] == 0))
                                        {
                                            break;
                                        }
                                        len += 2;
                                    }
                                    String s = Marshal.PtrToStringUni((IntPtr)pFileNames, len);
                                    items = s.Split(new char[] { (char)0 });
                                }
                            }
                            finally
                            {
                                GlobalUnlock(data.unionmember);
                            }
                            StringBuilder files = new StringBuilder();
                            foreach (string file in items)
                            {
                                if (System.IO.File.Exists(file))
                                {
                                    if (files.Length > 0)
                                    {
                                        files.Append('\0');
                                    }
                                    files.Append(file);
                                }
                            }
                            if (files.Length > 0)
                            {
                                _window.IWindow.OnDropFiles.Call(files.ToString());
                                return(S_OK);
                            }
                        }
                    }
                    else if (etcs[0].cfFormat == 13)
                    {
                        STGMEDIUM data;
                        pDataObject.GetData(ref etcs[0], out data);
                        String text = null;

                        if (data.tymed == TYMED.TYMED_HGLOBAL)
                        {
                            IntPtr hData = GlobalLock(data.unionmember);
                            try
                            {
                                int size = (int)GlobalSize(data.unionmember);
                                text = Marshal.PtrToStringUni(hData);
                            }
                            finally
                            {
                                GlobalUnlock(data.unionmember);
                            }
                        }

                        Hashtable data_json = null;
                        try
                        {
                            data_json = Utility.ParseJson(text) as Hashtable;
                        }
                        catch
                        {
                            data_json = null;
                        }

                        if (data_json != null && data_json.ContainsKey("__Type") && data_json.ContainsKey("__Data"))
                        {
                            string drop_type = data_json["__Type"].ToString();
                            string drop_data = data_json["__Data"].ToString();
                            _window.IWindow.OnDrop.CallAll(drop_type, drop_data);
                            return(S_OK);
                        }
                    }
                }
                if (m_pPreDropTarget != null)
                {
                    m_pPreDropTarget.Drop(pDataObject, grfKeyState, pt, ref pdwEffect);
                }
                return(S_OK);
            }
Esempio n. 17
0
        public static List <string> GetFiles(System.Runtime.InteropServices.ComTypes.IDataObject pDataObj)
        {
            System.Runtime.InteropServices.ComTypes.FORMATETC formatV = new System.Runtime.InteropServices.ComTypes.FORMATETC()
            {
                cfFormat = (Int16)DataFormats.GetFormat(NativeMethods.CFSTR_FILEDESCRIPTORW).Id,
                dwAspect = DVASPECT.DVASPECT_CONTENT,
                tymed    = TYMED.TYMED_HGLOBAL
            };
            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
            };

            STGMEDIUM medium;

            bool bVirtualData  = true;
            bool bVirtualShell = false;

            try
            {
                pDataObj.GetData(ref formatV, out medium);
            }
            catch (Exception)
            {
                if (pDataObj is System.Windows.Forms.DataObject)
                {
                    List <string> files1 = new List <string>();
                    //medium = new STGMEDIUM();
                    System.Windows.Forms.DataObject dob = (System.Windows.Forms.DataObject)pDataObj;
                    StringCollection z = (StringCollection)dob.GetData(typeof(StringCollection));
                    foreach (string s in z)
                    {
                        files1.Add(s);
                    }

                    /*
                     * if (dob.ContainsFileDropList())
                     * {
                     *  StringCollection c = dob.GetFileDropList();
                     *  foreach (string s in c)
                     *  {
                     *      files1.Add(s);
                     *  }
                     * }
                     * else
                     * {
                     *  string objFormat = dob.GetFormats().FirstOrDefault(x => x.Equals("FileDrop"));
                     *  if (!string.IsNullOrEmpty(objFormat))
                     *  {
                     *      object obj = dob.GetData("FileDrop");
                     *      if (obj is string)
                     *          files1.Add((string)obj);
                     *  }
                     * }
                     */
                    return(files1);
                }
                else
                {
                    int ret = pDataObj.QueryGetData(ref format);
                    if (ret > 0)
                    {
                        bVirtualShell = true;

                        Debug.WriteLine("!!!!SPECIAL FOLDER!!!!");
                        pDataObj.GetData(ref formatShell, out medium);
                    }
                    else
                    {
                        try
                        {
                            pDataObj.GetData(ref format, out medium);
                        }
                        catch (Exception)
                        {
                            bVirtualShell = true;

                            Debug.WriteLine("!!!!SPECIAL FOLDER!!!!");
                            pDataObj.GetData(ref formatShell, out medium);
                        }
                    }

                    /*
                     * if (ret != 0)
                     * {
                     *  Debug.WriteLine("------- GET FORMATS -------");
                     *  IEnumFORMATETC en = pDataObj.EnumFormatEtc(DATADIR.DATADIR_GET);
                     *  System.Runtime.InteropServices.ComTypes.FORMATETC[] fc = new System.Runtime.InteropServices.ComTypes.FORMATETC[10];
                     *  int[] fetched = new int[10];
                     *  int ret1 = en.Next(10, fc, fetched);
                     *  for (int i = 0; i < fetched[0]; i++)
                     *  {
                     *      DataFormats.Format f = DataFormats.GetFormat(fc[i].cfFormat);
                     *
                     *      string sn = f.Name;
                     *      Debug.WriteLine("FORMAT: " + sn);
                     *  }
                     *  Debug.WriteLine("---------------------------");
                     *
                     *  pDataObj.GetData(ref formatShell, out medium);
                     *  IntPtr ptr1;
                     *  ptr1 = medium.unionmember;
                     *  IntPtr ptrLock = NativeMethods.GlobalLock(ptr1);
                     *
                     *
                     *  List<IntPtr> lsUnk = ProcessCIDA(ptrLock);
                     *  foreach (IntPtr intPtr in lsUnk)
                     *  {
                     *      foreach (Environment.SpecialFolder suit in Enum.GetValues(typeof(Environment.SpecialFolder)))
                     *      {
                     *          var desktopPIDL = IntPtr.Zero;
                     *          int r = Shell32.SHGetSpecialFolderLocation(IntPtr.Zero, (int)suit, ref desktopPIDL);
                     *
                     *          string spath = Environment.GetFolderPath(suit);
                     *
                     *
                     *          string s1 = PidlManager.GetPidlDisplayName(desktopPIDL);
                     *          string s2 = PidlManager.GetPidlDisplayName(intPtr);
                     *
                     *          bool be = Shell32.ILIsEqual(intPtr, desktopPIDL);
                     *          if (be || s1.Equals(s2))
                     *          {
                     *              ItemIdList iptm = ItemIdList.Create(desktopPIDL);
                     *              byte[][] b = iptm.GetItemData();
                     *              string s = "finded!!!:" + suit;
                     *
                     *              ItemIdList iptm1 = ItemIdList.Create(intPtr);
                     *              byte[][] b1 = iptm1.GetItemData();
                     *          }
                     *      }
                     *
                     *      Shell32.ILFree(intPtr);
                     *  }
                     *
                     *  IntPtr ptrUnLock = NativeMethods.GlobalUnlock(ptrLock);
                     *
                     * }
                     * else
                     * {
                     *  pDataObj.GetData(ref format, out medium);
                     * }
                     */
                }

                bVirtualData = false;
            }

            IntPtr ptr;

            ptr = medium.unionmember;

            List <string> files = new List <string>();

            if (bVirtualData)
            {
                GetVirtualFileNamesFromDataObject(ptr, ref files);
            }
            else
            {
                if (!bVirtualShell)
                {
                    GetFileNamesFromDataObject(ptr, ref files);
                }
                else
                {
                    GetSystemVirtualFileNamesFromDataObject(ptr, ref files);
                }
            }

            NativeMethods.ReleaseStgMedium(ref medium);


            return(files);
        }
Esempio n. 18
0
        override public bool GetMTEF()
        {
            bool bReturn = false;

            if (!sdk.Init())
            {
                return(bReturn);
            }

            IDataObject dataObject = MathTypeSDK.getIDataObject();

            if (dataObject == null)
            {
                sdk.DeInit();
                return(bReturn);
            }

            FORMATETC formatEtc = new FORMATETC();
            STGMEDIUM stgMedium = new STGMEDIUM();

            try
            {
                // Setup the formatting information to use for the conversion.
                formatEtc.cfFormat = (Int16)DataFormats.GetFormat(strInTrans).Id;
                formatEtc.dwAspect = DVASPECT.DVASPECT_CONTENT;
                formatEtc.lindex   = -1;
                formatEtc.ptd      = (IntPtr)0;
                formatEtc.tymed    = TYMED.TYMED_HGLOBAL;

                // Setup the MathML content to convert
                stgMedium.unionmember    = Marshal.StringToHGlobalAuto(strEquation);
                stgMedium.tymed          = TYMED.TYMED_HGLOBAL;
                stgMedium.pUnkForRelease = 0;

                // Perform the conversion
                dataObject.SetData(ref formatEtc, ref stgMedium, false);

                // Set the format for the output
                formatEtc.cfFormat = (Int16)DataFormats.GetFormat("MathType EF").Id;
                formatEtc.dwAspect = DVASPECT.DVASPECT_CONTENT;
                formatEtc.lindex   = -1;
                formatEtc.ptd      = (IntPtr)0;
                formatEtc.tymed    = TYMED.TYMED_ISTORAGE;

                // Create a blank data structure to hold the converted result.
                stgMedium                = new STGMEDIUM();
                stgMedium.tymed          = TYMED.TYMED_NULL;
                stgMedium.pUnkForRelease = 0;

                // Get the conversion result in MTEF format
                dataObject.GetData(ref formatEtc, out stgMedium);
            }
            catch (COMException e)
            {
                Console.WriteLine("MathML conversion to MathType threw an exception: " + Environment.NewLine + e.ToString());
                sdk.DeInit();
                return(bReturn);
            }

            // The pointer now becomes a Handle reference.
            HandleRef handleRef = new HandleRef(null, stgMedium.unionmember);

            try
            {
                // Lock in the handle to get the pointer to the data
                IntPtr ptrToHandle = MathTypeSDK.GlobalLock(handleRef);

                // Get the size of the memory block
                m_iMTEF_Length = MathTypeSDK.GlobalSize(handleRef);

                // New an array of bytes and Marshal the data across.
                m_bMTEF = new byte[m_iMTEF_Length];
                Marshal.Copy(ptrToHandle, m_bMTEF, 0, m_iMTEF_Length);
                m_strMTEF = System.Text.ASCIIEncoding.ASCII.GetString(m_bMTEF);
                bReturn   = true;
            }
            catch (Exception e)
            {
                Console.WriteLine("Generation of image from MathType failed: " + Environment.NewLine + e.ToString());
            }
            finally
            {
                MathTypeSDK.GlobalUnlock(handleRef);
            }

            sdk.DeInit();
            return(bReturn);
        }
Esempio n. 19
0
        /// <summary>
        /// Returns the data associated with the specified data format at the specified index.
        /// </summary>
        /// <param name="format">A <see cref="string" /> that specifies the format of the data to retrieve.</param>
        /// <param name="index">A <see cref="int" /> value specifying the index at which to retrieve the data object from.</param>
        /// <returns>
        /// The data associated with the specified format from at the specified index, or <see langword="null" />.
        /// </returns>
        public byte[] GetData(string format, int index)
        {
            Check.ArgumentNull(format, nameof(format));
            Check.ArgumentOutOfRangeEx.GreaterEqual0(index, nameof(index));

            FORMATETC formatEtc = new FORMATETC
            {
                cfFormat = (short)DataFormats.GetFormat(format).Id,
                dwAspect = DVASPECT.DVASPECT_CONTENT,
                lindex   = index,
                ptd      = IntPtr.Zero,
                tymed    = TYMED.TYMED_ISTREAM | TYMED.TYMED_ISTORAGE | TYMED.TYMED_HGLOBAL
            };

            STGMEDIUM medium;

            ComDataObject.GetData(ref formatEtc, out medium);

            if (medium.tymed == TYMED.TYMED_ISTORAGE)
            {
                Native.IStorage   storage   = null;
                Native.IStorage   storage2  = null;
                Native.ILockBytes lockBytes = null;
                try
                {
                    storage = (Native.IStorage)Marshal.GetObjectForIUnknown(medium.unionmember);
                    Marshal.Release(medium.unionmember);
                    lockBytes = Native.CreateILockBytesOnHGlobal(IntPtr.Zero, true);
                    storage2  = Native.StgCreateDocfileOnILockBytes(lockBytes, 0x1012);

                    storage.CopyTo(0, null, IntPtr.Zero, storage2);
                    lockBytes.Flush();
                    storage2.Commit(0);

                    StatStg lockBytesStat;
                    lockBytes.Stat(out lockBytesStat, 1);
                    int lockBytesSize = (int)lockBytesStat.cbSize;

                    byte[] lockBytesContent = new byte[lockBytesSize];
                    lockBytes.ReadAt(0, lockBytesContent, lockBytesContent.Length, null);
                    return(lockBytesContent);
                }
                finally
                {
                    Marshal.ReleaseComObject(storage2);
                    Marshal.ReleaseComObject(lockBytes);
                    Marshal.ReleaseComObject(storage);
                }
            }
            else if (medium.tymed == TYMED.TYMED_ISTREAM)
            {
                IStream stream = null;
                try
                {
                    stream = (IStream)Marshal.GetObjectForIUnknown(medium.unionmember);
                    Marshal.Release(medium.unionmember);

                    StatStg streamStat;
                    stream.Stat(out streamStat, 0);
                    int streamSize = (int)streamStat.cbSize;

                    byte[] streamContent = new byte[streamSize];
                    stream.Read(streamContent, streamContent.Length, IntPtr.Zero);
                    return(streamContent);
                }
                finally
                {
                    Marshal.ReleaseComObject(stream);
                }
            }
            if (medium.tymed == TYMED.TYMED_HGLOBAL)
            {
                using MemoryStream memoryStream = GetDataFromHGlobalMethod.Invoke <MemoryStream>(OleDataObject, new object[] { DataFormats.GetFormat(formatEtc.cfFormat).Name, medium.unionmember });
                return(memoryStream.ToArray());
            }
            else
            {
                return(null);
            }
        }
        private List <DsObjectPickerItem> ProcessSelections(System.Runtime.InteropServices.ComTypes.IDataObject dataObj)
        {
            List <DsObjectPickerItem> selections = new List <DsObjectPickerItem>();

            if (dataObj == null)
            {
                return(selections);
            }

            STGMEDIUM stg = new STGMEDIUM();

            stg.tymed          = TYMED.TYMED_HGLOBAL;
            stg.unionmember    = IntPtr.Zero;
            stg.pUnkForRelease = null;

            FORMATETC fe = new FORMATETC();

            if (!this.DesignMode)
            {
                fe.cfFormat = (short)System.Windows.Forms.DataFormats.GetFormat(CfstrDsopDsSelectionList).Id;
            }
            fe.ptd      = IntPtr.Zero;
            fe.dwAspect = DVASPECT.DVASPECT_CONTENT;
            fe.lindex   = -1;
            fe.tymed    = TYMED.TYMED_HGLOBAL;

            dataObj.GetData(ref fe, out stg);

            IntPtr pDsSL = UnsafeNativeMethods.GlobalLock(stg.unionmember);

            try
            {
                IntPtr current = pDsSL;
                int    cnt     = Marshal.ReadInt32(current);

                if (cnt > 0)
                {
                    current = (IntPtr)((int)current + (Marshal.SizeOf(typeof(uint)) * 2));
                    for (int i = 0; i < cnt; i++)
                    {
                        UnsafeNativeMethods.DsSelection selection =
                            (UnsafeNativeMethods.DsSelection)Marshal.PtrToStructure(current,
                                                                                    typeof(UnsafeNativeMethods.DsSelection));
                        Marshal.DestroyStructure(current, typeof(UnsafeNativeMethods.DsSelection));

                        current = (IntPtr)((int)current + Marshal.SizeOf(typeof(UnsafeNativeMethods.DsSelection)));

                        DsObjectPickerItem item = new DsObjectPickerItem();
                        item.Name      = selection.pwzName;
                        item.Upn       = GetUpnFromSelection(selection);
                        item.ClassName = selection.pwzClass.ToLowerInvariant();
                        item.Sid       = GetSidFromUpn(item.Upn);
                        selections.Add(item);
                    }
                }
            }
            finally
            {
                if (stg.unionmember != IntPtr.Zero)
                {
                    UnsafeNativeMethods.GlobalUnlock(stg.unionmember);
                }
                UnsafeNativeMethods.ReleaseStgMedium(ref stg);
            }

            return(selections);
        }
Esempio n. 21
0
        public int DragDrop(System.Runtime.InteropServices.ComTypes.IDataObject pDataObj, int grfKeyState, BandObjectLib.POINT pt, ref DragDropEffects pdwEffect)
        {
            try {
                if (this.DragFileOver != null)
                {
                    DragEventArgs e = new DragEventArgs(null, grfKeyState, pt.x, pt.y, DragDropEffects.Move | DragDropEffects.Copy | DragDropEffects.Scroll, pdwEffect);
                    this.DragFileOver(null, e);
                    pdwEffect = e.Effect;
                }
                else
                {
                    pdwEffect = DragDropEffects.Copy;
                }
                if (pdwEffect != DragDropEffects.None)
                {
                    if (this.DragFileDrop != null)
                    {
                        IntPtr ptr;
                        byte[] buffer;
                        switch (this.DragFileDrop(out ptr, out buffer))
                        {
                        case -1:
                            return(0);

                        case 0: {
                            IShellFolder ppv   = null;
                            object       obj2  = null;
                            Guid         riid  = ExplorerGUIDs.IID_IShellFolder;
                            Guid         guid2 = ExplorerGUIDs.IID_IDropTarget;
                            using (IDLWrapper wrapper = new IDLWrapper(buffer)) {
                                if (wrapper.Available && wrapper.IsDropTarget)
                                {
                                    try {
                                        IntPtr ptr2;
                                        if (PInvoke.SHBindToParent(wrapper.PIDL, riid, out ppv, out ptr2) == 0)
                                        {
                                            uint     rgfReserved = 0;
                                            IntPtr[] apidl       = new IntPtr[] { ptr2 };
                                            if (ppv.GetUIObjectOf(ptr, 1, apidl, ref guid2, ref rgfReserved, out obj2) == 0)
                                            {
                                                _IDropTarget target = obj2 as _IDropTarget;
                                                if (target != null)
                                                {
                                                    DragDropEffects effects = pdwEffect;
                                                    if (target.DragEnter(pDataObj, this.iLastKeyState, pt, ref effects) == 0)
                                                    {
                                                        effects = pdwEffect;
                                                        if (target.DragOver(this.iLastKeyState, pt, ref effects) == 0)
                                                        {
                                                            if ((this.iLastKeyState & 2) != 0)
                                                            {
                                                                pdwEffect = DragDropEffects.Link | DragDropEffects.Move | DragDropEffects.Copy;
                                                            }
                                                            return(target.DragDrop(pDataObj, this.iLastKeyState, pt, ref pdwEffect));
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                    catch {
                                    }
                                    finally {
                                        if (ppv != null)
                                        {
                                            Marshal.ReleaseComObject(ppv);
                                        }
                                        if (obj2 != null)
                                        {
                                            Marshal.ReleaseComObject(obj2);
                                        }
                                        if (this.DragDropEnd != null)
                                        {
                                            this.DragDropEnd(this, EventArgs.Empty);
                                        }
                                    }
                                }
                            }
                            return(0);
                        }
                        }
                    }
                    FORMATETC format = new FORMATETC();
                    format.cfFormat = 15;
                    format.ptd      = IntPtr.Zero;
                    format.dwAspect = DVASPECT.DVASPECT_CONTENT;
                    format.lindex   = -1;
                    format.tymed    = TYMED.TYMED_HGLOBAL;
                    STGMEDIUM medium = new STGMEDIUM();
                    try {
                        pDataObj.GetData(ref format, out medium);
                        PInvoke.SendMessage(this.hwnd, 0x233, medium.unionmember, IntPtr.Zero);
                    }
                    catch {
                    }
                    finally {
                        PInvoke.ReleaseStgMedium(ref medium);
                    }
                }
            }
            finally {
                if (pDataObj != null)
                {
                    Marshal.FinalReleaseComObject(pDataObj);
                }
            }
            return(0);
        }
Esempio n. 22
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);
        }
Esempio n. 23
0
 public int DragEnter(IDataObject pDataObj, int grfKeyState, Point pt, ref DragDropEffects pdwEffect)
 {
     try {
         if(DragFileEnter != null) {
             FORMATETC format = new FORMATETC();
             format.cfFormat = 15;
             format.ptd = IntPtr.Zero;
             format.dwAspect = DVASPECT.DVASPECT_CONTENT;
             format.lindex = -1;
             format.tymed = TYMED.TYMED_HGLOBAL;
             if(pDataObj.QueryGetData(ref format) >= 0) {
                 STGMEDIUM medium = new STGMEDIUM();
                 try {
                     try {
                         pDataObj.GetData(ref format, out medium);
                         pdwEffect = DragFileEnter(medium.unionmember, pt, grfKeyState);
                     }
                     catch {
                         pdwEffect = DragDropEffects.None;
                     }
                     goto Label_00A0;
                 }
                 finally {
                     PInvoke.ReleaseStgMedium(ref medium);
                 }
             }
             pdwEffect = DragDropEffects.None;
         }
         else {
             pdwEffect = DragDropEffects.Copy;
         }
     }
     finally {
         if(pDataObj != null) {
             Marshal.FinalReleaseComObject(pDataObj);
         }
     }
     Label_00A0:
     return 0;
 }
Esempio n. 24
0
            /// <summary>
            ///  Uses IStream and retrieves the specified format from the bound IComDataObject.
            /// </summary>
            private unsafe object?GetDataFromOleIStream(string format)
            {
                FORMATETC formatetc = new FORMATETC();
                STGMEDIUM medium    = new STGMEDIUM();

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

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

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

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

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

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

                        return(GetDataFromHGLOBAL(format, hglobal));
                    }

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

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

                    Ole32.ReleaseStgMedium(ref medium);
                }
            }
Esempio n. 25
0
        /// <summary>
        /// Retrieves the data associated with the specified data format at the specified index.
        /// </summary>
        /// <param name="format">The format of the data to retrieve. See <see cref="T:System.Windows.Forms.DataFormats"></see> for predefined formats.</param>
        /// <param name="index">The index of the data to retrieve.</param>
        /// <returns>
        /// A <see cref="MemoryStream"/> containing the raw data for the specified data format at the specified index.
        /// </returns>
        public MemoryStream GetData(string format, int index)
        {
            //create a FORMATETC struct to request the data with
            var 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
            var medium = new STGMEDIUM();

            //using the Com IDataObject interface get the data using the defined FORMATETC
            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);
                    var iLockBytesSize = (int)iLockBytesStat.cbSize;

                    //read the data from the ILockBytes (unmanaged byte array) into a managed byte array
                    var 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);
                    var iStreamSize = (int)iStreamStat.cbSize;

                    //read the data from the IStream into a managed byte array
                    var 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)getDataFromHGLOBLALMethod.Invoke(oleUnderlyingDataObject, new object[] { DataFormats.GetFormat((short)formatetc.cfFormat).Name, medium.unionmember }));
            }

            return(null);
        }