private void GetEmbeddedObjectText(object embeddedObject, StringBuilder sbText) { string text; IAccessible acc = embeddedObject as IAccessible; if (acc != null) { text = acc.get_accName(NativeMethods.CHILD_SELF); if (!string.IsNullOrEmpty(text)) { sbText.Append(text); return; } } // Didn't get IAccessible (or didn't get a name from it). // Try the IDataObject technique instead... int hr = NativeMethods.S_FALSE; IDataObject dataObject = null; IOleObject oleObject = embeddedObject as IOleObject; if (oleObject != null) { // Try IOleObject::GetClipboardData (which returns an IDataObject) first... hr = oleObject.GetClipboardData(0, out dataObject); } // If that didn't work, try the embeddedObject as a IDataObject instead... if (hr != NativeMethods.S_OK) { dataObject = embeddedObject as IDataObject; } if (dataObject == null) { return; } // Got the IDataObject. Now query it for text formats. Try Unicode first... bool fGotUnicode = true; UnsafeNativeMethods.FORMATETC fetc = new UnsafeNativeMethods.FORMATETC(); fetc.cfFormat = DataObjectConstants.CF_UNICODETEXT; fetc.ptd = IntPtr.Zero; fetc.dwAspect = DataObjectConstants.DVASPECT_CONTENT; fetc.lindex = -1; fetc.tymed = DataObjectConstants.TYMED_HGLOBAL; UnsafeNativeMethods.STGMEDIUM med = new UnsafeNativeMethods.STGMEDIUM(); med.tymed = DataObjectConstants.TYMED_HGLOBAL; med.pUnkForRelease = IntPtr.Zero; med.hGlobal = IntPtr.Zero; hr = dataObject.GetData(ref fetc, ref med); if (hr != NativeMethods.S_OK || med.hGlobal == IntPtr.Zero) { // If we didn't get Unicode, try for ANSI instead... fGotUnicode = false; fetc.cfFormat = DataObjectConstants.CF_TEXT; hr = dataObject.GetData(ref fetc, ref med); } // Did we get anything? if (hr != NativeMethods.S_OK || med.hGlobal == IntPtr.Zero) { return; } //lock the memory, so data can be copied into IntPtr globalMem = UnsafeNativeMethods.GlobalLock(med.hGlobal); try { //error check for the memory pointer if (globalMem == IntPtr.Zero) { return; } unsafe { //get the string if (fGotUnicode) { text = new string((char *)globalMem); } else { text = new string((sbyte *)globalMem); } } sbText.Append(text); } finally { //unlock the memory UnsafeNativeMethods.GlobalUnlock(med.hGlobal); UnsafeNativeMethods.ReleaseStgMedium(ref med); } }