public override object ConvertManagedToNative(object managedValue, Com2PropertyDescriptor pd, ref bool cancelSet) { // Don't cancel the set cancelSet = false; if (_lastManaged?.Equals(managedValue) == true) { object target = _pictureRef?.Target; if (target != null) { return(target); } } // We have to build an IPicture if (managedValue != null) { BOOL own = BOOL.FALSE; Ole32.PICTDESC pictdesc; if (managedValue is Icon icon) { pictdesc = Ole32.PICTDESC.FromIcon(icon, copy: false); } else if (managedValue is Bitmap bitmap) { pictdesc = Ole32.PICTDESC.FromBitmap(bitmap); own = BOOL.TRUE; } else { Debug.Fail($"Unknown Image type: {managedValue.GetType().Name}"); return(null); } Guid iid = typeof(Ole32.IPicture).GUID; Ole32.IPicture pict = (Ole32.IPicture)Ole32.OleCreatePictureIndirect(ref pictdesc, ref iid, own); _lastManaged = managedValue; _lastNativeHandle = (IntPtr)pict.Handle; _pictureRef = new WeakReference(pict); return(pict); } else { _lastManaged = null; _lastNativeHandle = IntPtr.Zero; _pictureRef = null; return(null); } }
public override object ConvertNativeToManaged(object nativeValue, Com2PropertyDescriptor pd) { if (nativeValue == null) { return(null); } Debug.Assert(nativeValue is Ole32.IPicture, "nativevalue is not IPicture"); Ole32.IPicture nativePicture = (Ole32.IPicture)nativeValue; IntPtr handle = (IntPtr)nativePicture.Handle; if (_lastManaged != null && handle == _lastNativeHandle) { return(_lastManaged); } if (handle != IntPtr.Zero) { switch ((Ole32.PICTYPE)nativePicture.Type) { case Ole32.PICTYPE.ICON: _pictureType = typeof(Icon); _lastManaged = Icon.FromHandle(handle); break; case Ole32.PICTYPE.BITMAP: _pictureType = typeof(Bitmap); _lastManaged = Image.FromHbitmap(handle); break; default: Debug.Fail("Unknown picture type"); return(null); } _lastNativeHandle = handle; _pictureRef = new WeakReference(nativePicture); } else { _lastManaged = null; _pictureRef = null; } return(_lastManaged); }