Hello, I have an application where I insert one or more System.Drawing.Imaging.Metafile
s into a System.Windows.Forms.RichTextBox
. I would like to associate arbitrary appliction data with each Metafile image. This way I can recognize the identity of the inserted image later when the user right-clicks on the image and also retrieve information associated with the particular image. (Images may use the same base graphic so it is necessary to use something other than their pixels to distinguish them.) I'm open to suggestions of alternative ways to distinguish the images in a RichTextBox. I have a related question about using RTF annotations in a RichTextBox
.
I am unable to add any metadata to the image, however. The property .PropertyItems
is supposed to be a means of modifying metadata associated with the Metafile
. However whenever I access this property I get a NotImplementedException
. Following is the method I'm using to create the Metafile
and convert it to hexadecimal for insertion into the RTF \pict
control:
public enum MappingMode
{
MM_TEXT = 1,
MM_LOMETRIC = 2,
MM_HIMETRIC = 3,
MM_LOENGLISH = 4,
MM_HIENGLISH = 5,
MM_TWIPS = 6,
MM_ISOTROPIC = 7,
MM_ANISOTROPIC = 8
}
public static string ImageToMetafileHex(Forms.RichTextBox rtfBox, Drawing.Image image, MappingMode mappingMode)
{
string rtf = null;
using (IO.MemoryStream stream = new IO.MemoryStream())
using (Drawing.Graphics rtfBoxGraphics = rtfBox.CreateGraphics())
{
IntPtr pDeviceContext = rtfBoxGraphics.GetHdc();
using (Imaging.Metafile metafile = new Imaging.Metafile(stream, pDeviceContext))
{
using (Drawing.Graphics imageGraphics = Drawing.Graphics.FromImage(metafile))
{
imageGraphics.DrawImage(image, new Drawing.Rectangle(0, 0, image.Width, image.Height));
}
// Attempting to access metafile.PropertyItems anywhere triggers a NotImplementedException
// So how can we associate any application-data with it?
IntPtr pEnhancedMetafile = metafile.GetHenhmetafile();
// A call to EmfToWmfBits with a null buffer return the size of the
// buffer need to store the WMF bits. Use this to get the buffer
// size.
uint bufferSize = GdipEmfToWmfBits(pEnhancedMetafile, 0, null, mappingMode,
EmfToWmfBitsFlags.EmfToWmfBitsFlagsDefault);
byte[] buffer = new byte[bufferSize];
// A call to EmfToWmfBits with a valid buffer copies the bits into the
// buffer an returns the number of bits in the WMF.
uint convertedSize = GdipEmfToWmfBits(pEnhancedMetafile, bufferSize, buffer, mappingMode,
EmfToWmfBitsFlags.EmfToWmfBitsFlagsDefault);
StringBuilder rtfStringBuilder = new StringBuilder();
for (int i = 0; i < buffer.Length; ++i)
{
rtfStringBuilder.Append(String.Format("{0:X2}", buffer[i]));
}
rtf = rtfStringBuilder.ToString();
}
rtfBoxGraphics.ReleaseHdc(pDeviceContext);
}
return rtf;
}
Any help appreciated. TIA.