public static string[] IDataObjectToString(System.Windows.IDataObject Object) { object o = Object.GetData(System.Windows.DataFormats.StringFormat); object[] o2 = (object[])Object.GetData(System.Windows.DataFormats.FileDrop); if (o == null) { List<string> ret = new List<string>(); foreach (object file in o2) ret.Add(file.ToString()); return ret.ToArray(); } else return new string[] { (string)o }; }
private ToolboxItem CreateAxToolboxItem(System.Windows.Forms.IDataObject dataObject) { AxToolboxItem item = null; MemoryStream data = (MemoryStream) dataObject.GetData(axClipFormat, true); int length = (int) data.Length; byte[] buffer = new byte[length]; data.Read(buffer, 0, length); string clsid = Encoding.Default.GetString(buffer); int index = clsid.IndexOf("}"); clsid = clsid.Substring(0, index + 1); if (!this.IsSupportedActiveXControl(clsid)) { return null; } if (this.axTools != null) { item = (AxToolboxItem) this.axTools[clsid]; if (item != null) { bool traceVerbose = AxToolSwitch.TraceVerbose; return item; } } item = new AxToolboxItem(clsid); if (this.axTools == null) { this.axTools = new Hashtable(); } this.axTools.Add(clsid, item); return item; }
public static IEnumerable<File> Decode(System.Windows.IDataObject data) { IntPtr fileGroupDescriptorWPointer = IntPtr.Zero; try { //use the underlying IDataObject to get the FileGroupDescriptorW as a MemoryStream MemoryStream fileGroupDescriptorStream = (MemoryStream)data.GetData("FileGroupDescriptorW"); byte[] fileGroupDescriptorBytes = new byte[fileGroupDescriptorStream.Length]; fileGroupDescriptorStream.Read(fileGroupDescriptorBytes, 0, fileGroupDescriptorBytes.Length); fileGroupDescriptorStream.Close(); //copy the file group descriptor into unmanaged memory fileGroupDescriptorWPointer = Marshal.AllocHGlobal(fileGroupDescriptorBytes.Length); Marshal.Copy(fileGroupDescriptorBytes, 0, fileGroupDescriptorWPointer, fileGroupDescriptorBytes.Length); //marshal the unmanaged memory to to FILEGROUPDESCRIPTORW struct object fileGroupDescriptorObject = Marshal.PtrToStructure(fileGroupDescriptorWPointer, typeof(NativeMethods.FILEGROUPDESCRIPTORW)); NativeMethods.FILEGROUPDESCRIPTORW fileGroupDescriptor = (NativeMethods.FILEGROUPDESCRIPTORW)fileGroupDescriptorObject; //create a new array to store file names in of the number of items in the file group descriptor List<File> files = new List<File>(); //get the pointer to the first file descriptor IntPtr fileDescriptorPointer = (IntPtr)((int)fileGroupDescriptorWPointer + Marshal.SizeOf(fileGroupDescriptorWPointer)); //loop for the number of files acording to the file group descriptor for (int fileDescriptorIndex = 0; fileDescriptorIndex < fileGroupDescriptor.cItems; fileDescriptorIndex++) { //marshal the pointer top the file descriptor as a FILEDESCRIPTORW struct and get the file name NativeMethods.FILEDESCRIPTORW fileDescriptor = (NativeMethods.FILEDESCRIPTORW)Marshal.PtrToStructure(fileDescriptorPointer, typeof(NativeMethods.FILEDESCRIPTORW)); File file = new File(); file.Name = fileDescriptor.cFileName; file.Size = (long)fileDescriptor.nFileSizeLow + ((long)fileDescriptor.nFileSizeHigh << 32); files.Add(file); //move the file descriptor pointer to the next file descriptor fileDescriptorPointer = (IntPtr)((int)fileDescriptorPointer + Marshal.SizeOf(fileDescriptor)); } int index = 0; foreach (File f in files) { f.Content = GetData(data, FileContents, index++); } //return the array of files return files; } finally { //free unmanaged memory pointer Marshal.FreeHGlobal(fileGroupDescriptorWPointer); } }
public static void InvalidateDragImage(System.Windows.IDataObject dataObject) { if (!dataObject.GetDataPresent("DragWindow")) return; Advent.Common.Interop.NativeMethods.PostMessage(DataObjectExtensions.GetIntPtrFromData(dataObject.GetData("DragWindow")), 1027U, IntPtr.Zero, IntPtr.Zero); }
private ShellObject[] ParseShellIDListArray(System.Runtime.InteropServices.ComTypes.IDataObject pDataObj) { List<ShellObject> result = new List<ShellObject>(); System.Runtime.InteropServices.ComTypes.FORMATETC format = new System.Runtime.InteropServices.ComTypes.FORMATETC(); System.Runtime.InteropServices.ComTypes.STGMEDIUM medium = new System.Runtime.InteropServices.ComTypes.STGMEDIUM(); format.cfFormat = (short)ExplorerBrowser.RegisterClipboardFormat("Shell IDList Array"); format.dwAspect = System.Runtime.InteropServices.ComTypes.DVASPECT.DVASPECT_CONTENT; format.lindex = 0; format.ptd = IntPtr.Zero; format.tymed = System.Runtime.InteropServices.ComTypes.TYMED.TYMED_HGLOBAL; pDataObj.GetData(ref format, out medium); ExplorerBrowser.GlobalLock(medium.unionmember); try { ShellObject parentFolder = null; int count = Marshal.ReadInt32(medium.unionmember); int offset = 4; for (int n = 0; n <= count; ++n) { int pidlOffset = Marshal.ReadInt32(medium.unionmember, offset); int pidlAddress = (int)medium.unionmember + pidlOffset; if (n == 0) { parentFolder = ShellObjectFactory.Create(new IntPtr(pidlAddress)); } else { result.Add(ShellObjectFactory.Create(ExplorerBrowser.CreateItemWithParent(GetIShellFolder(parentFolder.NativeShellItem), new IntPtr(pidlAddress)))); } offset += 4; } } finally { Marshal.FreeHGlobal(medium.unionmember); } return result.ToArray(); }
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; }
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 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; }
void ch_ClipboardGrabbed(System.Windows.Forms.IDataObject dataObject) { try { IntPtr id; User32.GetWindowThreadProcessId(activeWindow, out id); activeProcess = Process.GetProcessById(id.ToInt32()); if (ExclusionslistController.Accept(activeWindow)) { var formats = dataObject.GetFormats(); DataEnabledListBoxItem n = null; var ItemsBox = mainWindow.ItemsBox; if (formats.Contains(DataFormats.Text)) { var text = Clipboard.GetText(); if (Settings.Default.OmitEmptyStrings && String.IsNullOrEmpty(text)) { return; } if (Settings.Default.OmitWhitespacesOnlyString && String.IsNullOrEmpty(text.Trim())) { return; } if (CheckDuplicates(ItemsBox, (obj) => (text as string) == (obj as string))) return; n = new TextDataLBI(Clipboard.GetDataObject()); } else if (formats.Contains(DataFormats.FileDrop)) { var files = dataObject.GetData(DataFormats.FileDrop) as string[]; if (CheckDuplicates(ItemsBox, (obj) => { string[] objasfiles = obj as string[]; if (objasfiles != null && objasfiles.Length == files.Length) { // we need this since order may nto be preserved // e.g. when user selects file from l-to-r and // and then r-to-l for (int i = 0; i < objasfiles.Length; i++) { if (!files.Contains(objasfiles[i])) return false; } return true; } return false; })) return; n = new FileDropsLBI(files); } else if (System.Windows.Clipboard.ContainsImage()) { System.Windows.Forms.IDataObject clipboardData = System.Windows.Forms.Clipboard.GetDataObject(); System.Drawing.Bitmap bitmap = (System.Drawing.Bitmap)clipboardData.GetData( System.Windows.Forms.DataFormats.Bitmap); if (CheckDuplicates(ItemsBox, (obj) => { var taghash = obj as ImageHash; if (taghash == null) { return false; } else return ImageHash.Compare(taghash, new ImageHash(bitmap)) == ImageHash.CompareResult.ciCompareOk; })) return; n = new ImageLBI(bitmap); } if (n != null) { ItemsBox.Items.Insert(0, n); n.ItemClicked += new ItemCopiedEventHandler(n_ItemClicked); } /* Console.WriteLine("\r\n\r\n"); for (int i = 0; i < ItemsBox.Items.Count; i++) { Console.WriteLine("{0}:{1}", i, (ItemsBox.Items[i] as ListBoxItem).Tag); }*/ } } catch (COMException) { MessageBox.Show("An error occured while performing clipboard operation (read)"); } }
static bool DoEnablePaste(ISolutionFolder container, System.Windows.IDataObject dataObject) { if (dataObject == null) { return false; } if (dataObject.GetDataPresent(typeof(ISolutionItem).ToString())) { Guid guid = Guid.Parse(dataObject.GetData(typeof(ISolutionItem).ToString()).ToString()); ISolutionItem solutionItem = container.ParentSolution.GetItemByGuid(guid); if (solutionItem == null || solutionItem == container) return false; if (solutionItem is ISolutionFolder) { return solutionItem.ParentFolder != container && !((ISolutionFolder)solutionItem).IsAncestorOf(container); } else { return solutionItem.ParentFolder != container; } } return false; }
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; }
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; }
/// <summary> /// Deserializes the data. /// </summary> /// <param name="data">The data.</param> /// <param name="format">The format.</param> /// <returns></returns> private string[] DeserializeData(System.Windows.Forms.IDataObject data, string format) { object obj = data.GetData(format); MemoryStream ms = obj as MemoryStream; if (ms != null) { // Récupération du nom du projet dans les données véhiculées string projectInfo = String.Empty; String str = Encoding.Unicode.GetString(ms.ToArray()); // Récupération des chaines textuelles au format c (0 de terminaison) StringBuilder sb = new StringBuilder(); for (int ix = 0; ix < str.Length; ix++) { char ch = str[ix]; if (ch == 0) // 0 final { if (sb.Length > 2) projectInfo = sb.ToString(); // On récupère la dernière chaine de plus de 2 car de long if (sb.Length != 0) sb = new StringBuilder(); // Nouvelle chaine continue; } sb.Append(ch); } return projectInfo.Split('|'); } return null; }
/// <summary> /// Gets the project item dropped. /// </summary> /// <param name="data">The data.</param> /// <returns></returns> public HierarchyNode GetProjectItemDropped(System.Windows.Forms.IDataObject data) { string[] infos = DeserializeData(data, ProjectItemReferenceFormat); string fileName = null; if (infos != null) fileName = infos[2]; else if (data.GetDataPresent("Text")) fileName = (string)data.GetData("Text"); if (fileName != null) return CurrentSolution.RecursiveFindByPath(fileName); return null; }
public static BitmapSource GetBestPossibletAlphaBitmapFromDataObject(System.Windows.IDataObject ob) { var formats = ob.GetFormats(); BitmapSource bmp = null; foreach (string f in formats) { if (f != "PNG" && f != "image/png") { // only PNG (GIMP) and image/png (haven't seen this in the wild but could be useful) continue; } var it = ob.GetData(f); var ms = it as MemoryStream; if (ms != null) { BitmapImage result = new BitmapImage(); result.BeginInit(); // According to MSDN, "The default OnDemand cache option retains access to the stream until the image is needed." // Force the bitmap to load right now so we can dispose the stream. result.CacheOption = BitmapCacheOption.OnLoad; result.StreamSource = ms; result.EndInit(); result.Freeze(); bmp = result; break; } } if (bmp == null) { foreach (string f in formats) { if (!f.ToLower().Contains("bitmap")) { continue; } var obj = ob.GetData(f) as BitmapSource; if (obj != null) { bmp = obj; break; } } } if (bmp == null) { bmp = WindowsClipboard.GetImage(); } bmp = TryFixAlphaChannel(bmp); return bmp; }
private static bool IsShowingLayered(System.Windows.IDataObject dataObject) { if (dataObject.GetDataPresent("IsShowingLayered", true)) { object data = dataObject.GetData("IsShowingLayered"); if (data != null) return DataObjectExtensions.GetBooleanFromData(data); } return false; }
private ToolboxItem CreateCfCodeToolboxItem(System.Windows.Forms.IDataObject dataObject) { object serializationData = null; serializationData = dataObject.GetData(OleDragDropHandler.NestedToolboxItemFormat, false); if (serializationData != null) { return (ToolboxItem) serializationData; } serializationData = dataObject.GetData(OleDragDropHandler.DataFormat, false); if (serializationData != null) { return new OleDragDropHandler.CfCodeToolboxItem(serializationData); } return null; }
//Note: GetdataPresent is not reliable for IDataObject that did not originate //from .Net. This rtn is called if it did, but we still don't use GetdataPresent. private void ProcessNetDataObject(System.Windows.Forms.IDataObject NetObject) { if (! (NetObject.GetData(typeof(ArrayList)) == null)) { Type AllowedType = typeof(CShItem); object oCSI; foreach (object tempLoopVar_oCSI in NetObject.GetData(typeof(ArrayList)) as IEnumerable) { oCSI = tempLoopVar_oCSI; if (! AllowedType.Equals(oCSI.GetType())) { m_Draglist = new ArrayList(); goto endOfForLoop; } else { m_Draglist.Add(oCSI); } } endOfForLoop: 1.GetHashCode() ; //nop } //Shell IDList Array is preferred to HDROP, see if we have one if (! (NetObject.GetData("Shell IDList Array") == null)) { //Get it and also mark that we had one m_StreamCIDA = NetObject.GetData("Shell IDList Array") as MemoryStream; //has one, ASSUME that it matchs what we may have gotten from // ArrayList, if we had one of those if (m_Draglist.Count < 1) //if we didn't have an ArrayList, have to build m_DragList { if (! MakeDragListFromCIDA()) //Could not make it { return; //leaving m_IsValid as false } } } //FileDrop is only used to build m_DragList if not already done if (m_Draglist.Count < 1) { if (! (NetObject.GetData("FileDrop") == null)) { string S; foreach (string tempLoopVar_S in NetObject.GetData("FileDrop", true) as IEnumerable) { S = tempLoopVar_S; try //if GetCShitem returns Nothing(it's failure marker) then catch it { m_Draglist.Add(ExpTreeLib.CShItem.GetCShItem(S)); } catch (Exception ex) //Some problem, throw the whole thing away { Debug.WriteLine("CMyDataObject -- Error in creating CShItem for " + S + "\r\n" + "Error is: " + ex.ToString()); m_Draglist = new ArrayList(); } } } } //At this point we must have a valid m_DragList if (m_Draglist.Count < 1) { return; //no list, not valid } //ensure that DataObject has a Shell IDList Array if (m_StreamCIDA == null) //wouldn't be Nothing if it had one { m_StreamCIDA = MakeShellIDArray(m_Draglist); NetObject.SetData("Shell IDList Array", true, m_StreamCIDA); } //At this point, we have a valid DragList and have ensured that the DataObject // has a CIDA. m_IsValid = true; return; }