This code works fine and can be called numerous times without any problems. However, if the bitmap is resized (made bigger), I get an access violation. This is not the case if the bimap is made smaller.
I can confirm that the BMPSize & BitmapBytes array size tally at all times.
Can anyone spread any light on this, please?
public void SetBitmap(Bitmap bmp) { UInt32 BMPSize = Convert.ToUInt32(bmp.Height * bmp.Width * 4); BMPSize += 0x36; if (!FileMappingCreated) { MemoryFileHandle = CreateFileMapping((IntPtr)0, (IntPtr)0, PageProtection.ReadWrite, 0, BMPSize, SharedName); if (MemoryFileHandle != null) { SetNamedSecurityInfo(SharedName, SE_OBJECT_TYPE.SE_KERNEL_OBJECT, SECURITY_INFORMATION.DACL_SECURITY_INFORMATION, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero); ViewFile = MapViewOfFile(MemoryFileHandle, FILE_MAP_WRITE, 0, 0, 0); if (MemoryFileHandle == IntPtr.Zero) { CloseHandle(MemoryFileHandle); } else { FileMappingCreated = true; } } } MemoryStream stream = new MemoryStream(); bmp.Save(stream, ImageFormat.Bmp); byte[] BitmapBytes = stream.ToArray(); // BMP SIZE Value 4bytes long see internet for DIB structure. byte[] DIBImageSize = null; int ImageSizeAddress = 0x22; DIBImageSize = BitConverter.GetBytes(Convert.ToInt32(BMPSize)); // put DIBImageSize into array starting at address 0x22 for (int i = 0; i < DIBImageSize.Length; i++) { BitmapBytes[ImageSizeAddress] = DIBImageSize; ImageSizeAddress++; } // THIS IS THE LINE THAT FAILS Marshal.Copy(BitmapBytes, 0, ViewFile, Convert.ToInt32(BMPSize)); BitmapBytes = null; DIBImageSize = null; FileMappingCreated = false; }