-
-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathFormatConverters.cs
1132 lines (968 loc) · 46.5 KB
/
FormatConverters.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using EditClipboardContents;
using System;
using System.Collections.Generic;
using System.Drawing.Imaging;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
// My classes
using static EditClipboardContents.ClipboardFormats;
using System.Windows.Forms;
using System.Xml.Linq;
using System.Runtime.InteropServices.ComTypes;
// Disable IDE warnings that showed up after going from C# 7 to C# 9
#pragma warning disable IDE0079 // Disable message about unnecessary suppression
#pragma warning disable IDE0063 // Disable messages about Using expression simplification
#pragma warning disable IDE0090 // Disable messages about New expression simplification
#pragma warning disable IDE0028,IDE0300,IDE0305 // Disable message about collection initialization
#pragma warning disable IDE0066 // Disable message about switch case expression
// Nullable reference types
#nullable enable
namespace EditClipboardContents
{
public static partial class FormatConverters
{
public static IntPtr AllocateGeneralHandle_FromRawData(byte[]? data)
{
if (data == null || data.Length == 0)
{
Console.WriteLine("No data to allocate and copy");
return IntPtr.Zero;
}
IntPtr hGlobal = NativeMethods.GlobalAlloc(NativeMethods.GMEM_MOVEABLE, (UIntPtr)data.Length);
if (hGlobal != IntPtr.Zero)
{
IntPtr pGlobal = NativeMethods.GlobalLock(hGlobal);
if (pGlobal != IntPtr.Zero)
{
try
{
Marshal.Copy(data, 0, pGlobal, data.Length);
}
catch(Exception ex)
{
Console.WriteLine($"Error in AllocateGeneralHandle_FromRawData: {ex.Message}");
}
finally
{
NativeMethods.GlobalUnlock(hGlobal);
}
}
else
{
NativeMethods.GlobalFree(hGlobal);
hGlobal = IntPtr.Zero;
Console.WriteLine("Failed to lock memory");
}
}
else
{
Console.WriteLine("Failed to allocate memory");
}
return hGlobal;
}
public static IntPtr Bitmap_hBitmapHandle_FromHandle(IntPtr hBitmap)
{
try
{
BITMAP bmp = new BITMAP();
NativeMethods.GetObject(hBitmap, Marshal.SizeOf(typeof(BITMAP)), ref bmp);
IntPtr hBitmapCopy = NativeMethods.CreateBitmap(bmp.bmWidth, bmp.bmHeight, bmp.bmPlanes, bmp.bmBitsPixel, IntPtr.Zero);
IntPtr hdcScreen = NativeMethods.GetDC(IntPtr.Zero);
IntPtr hdcSrc = NativeMethods.CreateCompatibleDC(hdcScreen);
IntPtr hdcDest = NativeMethods.CreateCompatibleDC(hdcScreen);
IntPtr hOldSrcBitmap = NativeMethods.SelectObject(hdcSrc, hBitmap);
IntPtr hOldDestBitmap = NativeMethods.SelectObject(hdcDest, hBitmapCopy);
NativeMethods.BitBlt(hdcDest, 0, 0, bmp.bmWidth, bmp.bmHeight, hdcSrc, 0, 0, 0x00CC0020 /* SRCCOPY */);
NativeMethods.SelectObject(hdcSrc, hOldSrcBitmap);
NativeMethods.SelectObject(hdcDest, hOldDestBitmap);
NativeMethods.DeleteDC(hdcSrc);
NativeMethods.DeleteDC(hdcDest);
NativeMethods.ReleaseDC(IntPtr.Zero, hdcScreen);
return hBitmapCopy;
}
catch (Exception ex)
{
MessageBox.Show($"Error while trying to copy HBITMAP: {ex.Message}", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return IntPtr.Zero;
}
}
public static IntPtr BitmapDIB_hGlobalHandle_FromHandle(IntPtr hDib)
{
UIntPtr size = NativeMethods.GlobalSize(hDib);
IntPtr hGlobal = NativeMethods.GlobalAlloc(NativeMethods.GMEM_MOVEABLE, size);
if (hGlobal != IntPtr.Zero)
{
IntPtr pGlobal = NativeMethods.GlobalLock(hGlobal);
IntPtr pData = NativeMethods.GlobalLock(hDib);
if (pGlobal != IntPtr.Zero && pData != IntPtr.Zero)
{
NativeMethods.CopyMemory(pGlobal, pData, size);
NativeMethods.GlobalUnlock(hDib);
NativeMethods.GlobalUnlock(hGlobal);
}
else
{
NativeMethods.GlobalFree(hGlobal);
hGlobal = IntPtr.Zero;
}
}
return hGlobal;
}
public static byte[]? EnhMetafile_RawData_FromHandle(IntPtr hEnhMetaFile)
{
if (hEnhMetaFile == IntPtr.Zero)
{
return null;
}
uint size = NativeMethods.GetEnhMetaFileBits(hEnhMetaFile, 0, null);
if (size > 0)
{
byte[] data = new byte[size];
if (NativeMethods.GetEnhMetaFileBits(hEnhMetaFile, size, data) == size)
{
return data;
}
}
return null;
}
public static byte[]? MetafilePict_RawData_FromHandle(IntPtr hMetafilePict)
{
IntPtr pMetafilePict = NativeMethods.GlobalLock(hMetafilePict);
if (pMetafilePict != IntPtr.Zero)
{
try
{
METAFILEPICT mfp = (METAFILEPICT)Marshal.PtrToStructure(pMetafilePict, typeof(METAFILEPICT));
uint metafileSize = NativeMethods.GetMetaFileBitsEx(mfp.hMF, 0, null);
if (metafileSize > 0)
{
byte[] metafileData = new byte[metafileSize];
if (NativeMethods.GetMetaFileBitsEx(mfp.hMF, metafileSize, metafileData) == metafileSize)
{
int metaFilePictHeaderSize = Marshal.SizeOf(typeof(METAFILEPICT)) - IntPtr.Size; // Subtract IntPtr.Size we'll replace with the actual metafile data
byte[] fullData = new byte[metaFilePictHeaderSize + metafileSize];
Marshal.Copy(pMetafilePict, fullData, 0, metaFilePictHeaderSize);
Buffer.BlockCopy(metafileData, 0, fullData, metaFilePictHeaderSize, (int)metafileSize);
return fullData;
}
}
}
catch (Exception ex)
{
MessageBox.Show($"Error while trying to read METAFILEPICT from memory: {ex.Message}", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
NativeMethods.GlobalUnlock(hMetafilePict);
}
}
return null;
}
public static byte[]? CF_HDROP_RawData_FromHandle(IntPtr hDrop)
{
// Lock the global memory object to access the data
IntPtr pDropFiles = NativeMethods.GlobalLock(hDrop);
if (pDropFiles == IntPtr.Zero)
{
return null;
}
try
{
// Get the size of the global memory object
int globalSize = (int)NativeMethods.GlobalSize(hDrop);
// Marshal the DROPFILES_OBJ structure from the memory
DROPFILES dropFiles = Marshal.PtrToStructure<DROPFILES>(pDropFiles);
// Ensure dropFiles.pFiles is within a reasonable range. pFiles defines the offset to the file names, so it should be less than the size of the global memory object.
if (dropFiles.pFiles <= 0 || dropFiles.pFiles > globalSize)
{
Console.WriteLine($"Invalid pFiles value: {dropFiles.pFiles}");
return null;
}
// Ensure the memory we're trying to access is within the bounds of the allocated global memory
int dropFilesStructSize = Marshal.SizeOf<DROPFILES>();
if (dropFilesStructSize + dropFiles.pFiles > globalSize)
{
Console.WriteLine("Attempting to access memory beyond the allocated global memory");
return null;
}
byte[] managedArray = new byte[dropFiles.pFiles];
// Now we can safely copy the memory
Marshal.Copy(pDropFiles, managedArray, 0, (int)dropFiles.pFiles); // Need to cast Dword to int32 because DWORD is uint32 and Marshal.Copy only takes int32 as the length parameter
// Determine if the file names are Unicode
bool isUnicode = dropFiles.fWide != 0;
// Get the number of files
uint fileCount = NativeMethods.DragQueryFile(hDrop, 0xFFFFFFFF, null, 0);
// Prepare to calculate the total size
List<byte> rawDataList = new List<byte>();
// Get the size of the DROPFILES_OBJ structure
int dropFilesSize = Marshal.SizeOf(typeof(DROPFILES));
// Copy the DROPFILES_OBJ structure to rawDataList
byte[] dropFilesBytes = new byte[dropFilesSize];
Marshal.Copy(pDropFiles, dropFilesBytes, 0, dropFilesSize);
rawDataList.AddRange(dropFilesBytes);
// For each file, get its path and add to rawDataList
for (uint i = 0; i < fileCount; i++)
{
uint pathLength = NativeMethods.DragQueryFile(hDrop, i, null, 0) + 1; // +1 for null terminator
if (isUnicode)
{
// Unicode
StringBuilder path = new StringBuilder((int)pathLength);
NativeMethods.DragQueryFile(hDrop, i, path, pathLength);
byte[] pathBytes = Encoding.Unicode.GetBytes(path.ToString());
rawDataList.AddRange(pathBytes);
// Add null terminator (2 bytes for Unicode)
rawDataList.AddRange(new byte[] { 0, 0 });
}
else
{
// ANSI
StringBuilder path = new StringBuilder((int)pathLength);
NativeMethods.DragQueryFileA(hDrop, i, path, pathLength);
byte[] pathBytes = Encoding.Default.GetBytes(path.ToString());
rawDataList.AddRange(pathBytes);
// Add null terminator
rawDataList.Add(0);
}
}
// Add final null terminator
if (isUnicode)
{
rawDataList.AddRange(new byte[] { 0, 0 });
}
else
{
rawDataList.Add(0);
}
// Convert the rawDataList to a byte array
return rawDataList.ToArray();
}
catch (Exception ex)
{
Console.WriteLine($"Error in CF_HDROP_RawData_FromHandle: {ex.Message}");
MessageBox.Show($"Error in CF_HDROP_RawData_FromHandle: {ex.Message}", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return null;
}
finally
{
// Always unlock the global memory object
NativeMethods.GlobalUnlock(hDrop);
}
}
public static IntPtr CF_HDROP_Handle_FromRawData(byte[]? rawData)
{
if (rawData == null || rawData.Length < Marshal.SizeOf(typeof(DROPFILES)))
{
return IntPtr.Zero;
}
// Lock rawData for pinning in memory
GCHandle handle = GCHandle.Alloc(rawData, GCHandleType.Pinned);
try
{
// Get pointer to the DROPFILES_OBJ structure in rawData
IntPtr pRawData = handle.AddrOfPinnedObject();
// Marshal the DROPFILES_OBJ structure from rawData
DROPFILES dropFiles = Marshal.PtrToStructure<DROPFILES>(pRawData);
// The file names start after the DROPFILES_OBJ structure
int fileListOffset = (int)dropFiles.pFiles;
// Calculate the length of the file names (rest of the rawData)
int fileNamesLength = rawData.Length - fileListOffset;
// Allocate global memory for the new clipboard data
IntPtr hGlobal = NativeMethods.GlobalAlloc(NativeMethods.GMEM_MOVEABLE | NativeMethods.GMEM_ZEROINIT, (UIntPtr)rawData.Length);
if (hGlobal == IntPtr.Zero)
return IntPtr.Zero;
IntPtr pGlobal = NativeMethods.GlobalLock(hGlobal);
if (pGlobal == IntPtr.Zero)
{
NativeMethods.GlobalFree(hGlobal);
return IntPtr.Zero;
}
try
{
// Copy the DROPFILES_OBJ structure to the global memory
Marshal.StructureToPtr(dropFiles, pGlobal, false);
// Copy the file names to the global memory
Marshal.Copy(rawData, fileListOffset, IntPtr.Add(pGlobal, fileListOffset), fileNamesLength);
}
finally
{
NativeMethods.GlobalUnlock(hGlobal);
}
return hGlobal;
}
finally
{
handle.Free();
}
}
public const uint GMEM_MOVEABLE = 0x0002; // Delete this later
public static IntPtr MetafilePict_Handle_FromRawData(byte[]? rawData)
{
if (rawData == null || rawData.Length <= Marshal.SizeOf<METAFILEPICT>())
return IntPtr.Zero;
IntPtr hGlobalMetafilePict = IntPtr.Zero;
IntPtr hMetafile = IntPtr.Zero;
IntPtr pMetafile = IntPtr.Zero;
IntPtr pMetafilePict = IntPtr.Zero;
IntPtr hActualMetafile = IntPtr.Zero;
try
{
// First allocate and create the metafile
int headerSize = Marshal.SizeOf<METAFILEPICT>() - IntPtr.Size;
int metafileDataSize = rawData.Length - headerSize;
byte[] metaFileData = new byte[metafileDataSize];
// Copy the metafile data portion
Array.Copy(rawData, headerSize, metaFileData, 0, metafileDataSize);
// Allocate memory for the metafile bits
hMetafile = NativeMethods.GlobalAlloc(GMEM_MOVEABLE, (UIntPtr)metafileDataSize);
if (hMetafile == IntPtr.Zero)
throw new OutOfMemoryException("Failed to allocate memory for metafile.");
// Lock and copy the metafile bits
pMetafile = NativeMethods.GlobalLock(hMetafile);
if (pMetafile == IntPtr.Zero)
throw new InvalidOperationException("Failed to lock metafile memory.");
Marshal.Copy(metaFileData, 0, pMetafile, metafileDataSize);
// Create the actual metafile while memory is still locked
hActualMetafile = NativeMethods.SetMetaFileBitsEx((uint)metafileDataSize, pMetafile);
if (hActualMetafile == IntPtr.Zero)
{
int error = Marshal.GetLastWin32Error();
string errorMessage = Utils.GetWin32ErrorMessage(error);
throw new InvalidOperationException($"Failed to create metafile from bits. Error {error} - {errorMessage}");
}
// Now create the METAFILEPICT structure
hGlobalMetafilePict = NativeMethods.GlobalAlloc(GMEM_MOVEABLE, (UIntPtr)Marshal.SizeOf<METAFILEPICT>());
if (hGlobalMetafilePict == IntPtr.Zero)
throw new OutOfMemoryException("Failed to allocate memory for METAFILEPICT.");
pMetafilePict = NativeMethods.GlobalLock(hGlobalMetafilePict);
if (pMetafilePict == IntPtr.Zero)
throw new InvalidOperationException("Failed to lock METAFILEPICT memory.");
// Create and copy the METAFILEPICT structure
METAFILEPICT mfp = new METAFILEPICT
{
mm = BitConverter.ToInt32(rawData, Marshal.OffsetOf<METAFILEPICT>(nameof(METAFILEPICT.mm)).ToInt32()),
xExt = BitConverter.ToInt32(rawData, Marshal.OffsetOf<METAFILEPICT>(nameof(METAFILEPICT.xExt)).ToInt32()),
yExt = BitConverter.ToInt32(rawData, Marshal.OffsetOf<METAFILEPICT>(nameof(METAFILEPICT.yExt)).ToInt32()),
hMF = hActualMetafile
};
Marshal.StructureToPtr(mfp, pMetafilePict, false);
// Transfer ownership of hActualMetafile to the METAFILEPICT structure
hActualMetafile = IntPtr.Zero;
return hGlobalMetafilePict;
}
catch (Exception ex)
{
// Clean up on failure
if (hActualMetafile != IntPtr.Zero)
NativeMethods.DeleteMetaFile(hActualMetafile);
if (hGlobalMetafilePict != IntPtr.Zero)
NativeMethods.GlobalFree(hGlobalMetafilePict);
Console.WriteLine($"Error in MetafilePict_Handle_FromRawData: {ex.Message}");
throw;
}
finally
{
// Clean up temporary resources
if (pMetafilePict != IntPtr.Zero)
NativeMethods.GlobalUnlock(hGlobalMetafilePict);
if (pMetafile != IntPtr.Zero)
NativeMethods.GlobalUnlock(hMetafile);
if (hMetafile != IntPtr.Zero)
NativeMethods.GlobalFree(hMetafile);
}
}
public static IntPtr EnhMetafile_Handle_FromRawData(byte[]? rawData)
{
if (rawData == null || rawData.Length == 0)
{
return IntPtr.Zero;
}
using (MemoryStream ms = new MemoryStream(rawData))
{
IntPtr hemf = NativeMethods.SetEnhMetaFileBits((uint)rawData.Length, rawData);
if (hemf != IntPtr.Zero)
{
IntPtr hemfCopy = NativeMethods.CopyEnhMetaFile(hemf, null);
NativeMethods.DeleteEnhMetaFile(hemf);
return hemfCopy;
}
}
return IntPtr.Zero;
}
public static Bitmap BitmapFile_From_CF_DIBV5_RawData(byte[] data)
{
if (data == null)
throw new ArgumentNullException(nameof(data));
GCHandle handle = GCHandle.Alloc(data, GCHandleType.Pinned);
try
{
BITMAPV5HEADER bmi = (BITMAPV5HEADER)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(BITMAPV5HEADER));
int width = Math.Abs(bmi.bV5Width); // Ensure positive width
int height = Math.Abs(bmi.bV5Height); // Ensure positive height
int headerSize = (int)Math.Min(bmi.bV5Size, (uint)Marshal.SizeOf(typeof(BITMAPV5HEADER)));
PixelFormat pixelFormat;
int paletteSize = 0;
switch (bmi.bV5BitCount)
{
case 1:
pixelFormat = PixelFormat.Format1bppIndexed;
paletteSize = 2 * Marshal.SizeOf(typeof(RGBQUAD));
break;
case 4:
pixelFormat = PixelFormat.Format4bppIndexed;
paletteSize = 16 * Marshal.SizeOf(typeof(RGBQUAD));
break;
case 8:
pixelFormat = PixelFormat.Format8bppIndexed;
paletteSize = 256 * Marshal.SizeOf(typeof(RGBQUAD));
break;
case 16:
pixelFormat = PixelFormat.Format16bppRgb555;
break;
case 24:
pixelFormat = PixelFormat.Format24bppRgb;
break;
case 32:
pixelFormat = PixelFormat.Format32bppArgb;
break;
default:
throw new NotSupportedException($"Bit depth {bmi.bV5BitCount} is not supported.");
}
int stride = ((width * bmi.bV5BitCount + 31) / 32) * 4;
bool isTopDown = bmi.bV5Height < 0;
IntPtr scan0 = new IntPtr(handle.AddrOfPinnedObject().ToInt64() + bmi.bV5Size + paletteSize);
if (!isTopDown)
{
scan0 = new IntPtr(scan0.ToInt64() + (height - 1) * stride);
stride = -stride;
}
Bitmap bitmap = new Bitmap(width, height, stride, pixelFormat, scan0);
if (pixelFormat == PixelFormat.Format8bppIndexed)
{
ColorPalette palette = bitmap.Palette;
IntPtr palettePtr = new IntPtr(handle.AddrOfPinnedObject().ToInt64() + bmi.bV5Size);
for (int i = 0; i < 256; i++)
{
RGBQUAD colorQuad = (RGBQUAD)Marshal.PtrToStructure(new IntPtr(palettePtr.ToInt64() + i * Marshal.SizeOf(typeof(RGBQUAD))), typeof(RGBQUAD));
palette.Entries[i] = Color.FromArgb(colorQuad.rgbRed, colorQuad.rgbGreen, colorQuad.rgbBlue);
}
bitmap.Palette = palette;
}
// Create a new bitmap to return, because the original one is tied to the pinned memory
Bitmap result = new Bitmap(bitmap);
return result;
}
catch (Exception ex)
{
Console.WriteLine($"Error in CF_DIBV5ToBitmap: {ex.Message}");
throw;
}
finally
{
handle.Free();
}
}
public static Bitmap Bitmap_From_CF_BITMAP_RawData(byte[] rawData)
{
if (rawData == null)
throw new ArgumentNullException(nameof(rawData));
// Get the offset of bmBits in the BITMAP structure
int bmBitsOffset = Marshal.OffsetOf<BITMAP>("bmBits").ToInt32();
if (rawData.Length <= bmBitsOffset)
throw new ArgumentException("Invalid raw data", nameof(rawData));
// Extract the BITMAP_HEADER from rawData
byte[] bitmapHeaderData = new byte[bmBitsOffset];
Array.Copy(rawData, 0, bitmapHeaderData, 0, bmBitsOffset);
_BitmapHeader bitmapHeader;
GCHandle headerHandle = GCHandle.Alloc(bitmapHeaderData, GCHandleType.Pinned);
try
{
bitmapHeader = Marshal.PtrToStructure<_BitmapHeader>(headerHandle.AddrOfPinnedObject());
}
finally
{
headerHandle.Free();
}
// Extract the bitmap bits from rawData
int bitsSize = rawData.Length - bmBitsOffset;
byte[] bitmapBits = new byte[bitsSize];
Array.Copy(rawData, bmBitsOffset, bitmapBits, 0, bitsSize);
int width = bitmapHeader.bmWidth;
int height = Math.Abs(bitmapHeader.bmHeight);
bool isBottomUp = bitmapHeader.bmHeight > 0;
// Determine the pixel format
PixelFormat pixelFormat;
switch (bitmapHeader.bmBitsPixel)
{
case 1:
pixelFormat = PixelFormat.Format1bppIndexed;
break;
case 4:
pixelFormat = PixelFormat.Format4bppIndexed;
break;
case 8:
pixelFormat = PixelFormat.Format8bppIndexed;
break;
case 16:
pixelFormat = PixelFormat.Format16bppRgb565; // Adjust as needed
break;
case 24:
pixelFormat = PixelFormat.Format24bppRgb;
break;
case 32:
pixelFormat = PixelFormat.Format32bppArgb; // Adjust based on actual alpha usage
break;
default:
throw new NotSupportedException($"Bit depth {bitmapHeader.bmBitsPixel} is not supported.");
}
Bitmap bitmap = new Bitmap(width, height, pixelFormat);
BitmapData bitmapData = bitmap.LockBits(
new Rectangle(0, 0, width, height),
ImageLockMode.WriteOnly,
pixelFormat);
try
{
int bytesPerPixel = bitmapHeader.bmBitsPixel / 8;
int sourceStride = bitmapHeader.bmWidthBytes; // Stride from the BITMAP structure
int destStride = bitmapData.Stride; // Stride of the locked bitmap
// Ensure source stride is correctly aligned
int expectedSourceStride = ((bitmapHeader.bmWidth * bitmapHeader.bmBitsPixel + 31) / 32) * 4;
if (sourceStride != expectedSourceStride)
{
sourceStride = expectedSourceStride;
}
// Copy the bitmap bits into the Bitmap object
for (int y = 0; y < height; y++)
{
int sourceY = isBottomUp ? (height - 1 - y) : y;
int sourceIndex = sourceY * sourceStride;
IntPtr destPtr = new IntPtr(bitmapData.Scan0.ToInt64() + y * destStride);
if (sourceIndex + sourceStride > bitmapBits.Length)
throw new ArgumentException("Bitmap bits are not sufficient for the specified dimensions.");
Marshal.Copy(bitmapBits, sourceIndex, destPtr, Math.Min(sourceStride, destStride));
}
}
finally
{
bitmap.UnlockBits(bitmapData);
}
return bitmap;
}
public static Bitmap BitmapFile_From_CF_DIB_RawData(byte[] data)
{
GCHandle handle = GCHandle.Alloc(data, GCHandleType.Pinned);
try
{
var bmi = (BITMAPINFO)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(BITMAPINFO));
int width = bmi.bmiHeader.biWidth;
int height = Math.Abs(bmi.bmiHeader.biHeight); // Handle both top-down and bottom-up DIBs
PixelFormat pixelFormat;
int paletteSize = 0;
switch (bmi.bmiHeader.biBitCount)
{
case 1:
pixelFormat = PixelFormat.Format1bppIndexed;
paletteSize = 2 * Marshal.SizeOf(typeof(RGBQUAD));
break;
case 4:
pixelFormat = PixelFormat.Format4bppIndexed;
paletteSize = 16 * Marshal.SizeOf(typeof(RGBQUAD));
break;
case 8:
pixelFormat = PixelFormat.Format8bppIndexed;
paletteSize = 256 * Marshal.SizeOf(typeof(RGBQUAD));
break;
case 16:
pixelFormat = PixelFormat.Format16bppRgb555;
break;
case 24:
pixelFormat = PixelFormat.Format24bppRgb;
break;
case 32:
pixelFormat = PixelFormat.Format32bppArgb;
break;
default:
throw new NotSupportedException($"Bit depth {bmi.bmiHeader.biBitCount} is not supported.");
}
int stride = ((width * bmi.bmiHeader.biBitCount + 31) / 32) * 4;
IntPtr scan0 = new IntPtr(handle.AddrOfPinnedObject().ToInt64() + Marshal.SizeOf(typeof(BITMAPINFOHEADER)) + paletteSize);
if (bmi.bmiHeader.biHeight > 0) // Top-up DIB
{
scan0 = new IntPtr(scan0.ToInt64() + (height - 1) * stride);
stride = -stride;
}
Bitmap bitmap = new Bitmap(width, height, stride, pixelFormat, scan0);
if (pixelFormat == PixelFormat.Format8bppIndexed)
{
ColorPalette palette = bitmap.Palette;
IntPtr palettePtr = new IntPtr(handle.AddrOfPinnedObject().ToInt64() + Marshal.SizeOf(typeof(BITMAPINFOHEADER)));
for (int i = 0; i < 256; i++)
{
RGBQUAD colorQuad = (RGBQUAD)Marshal.PtrToStructure(new IntPtr(palettePtr.ToInt64() + i * Marshal.SizeOf(typeof(RGBQUAD))), typeof(RGBQUAD));
palette.Entries[i] = Color.FromArgb(colorQuad.rgbRed, colorQuad.rgbGreen, colorQuad.rgbBlue);
}
bitmap.Palette = palette;
}
// Create a new bitmap to return, because the original one is tied to the pinned memory
Bitmap result = new Bitmap(bitmap);
return result;
}
finally
{
handle.Free();
}
}
public static byte[]? DIBits_From_HBitmap(IntPtr hBitmap)
{
BITMAPINFO bmi = new BITMAPINFO();
bmi.bmiHeader.biSize = (uint)Marshal.SizeOf(typeof(BITMAPINFOHEADER));
IntPtr hDC = NativeMethods.CreateCompatibleDC(IntPtr.Zero);
IntPtr hOldBitmap = NativeMethods.SelectObject(hDC, hBitmap);
try
{
// Get the bitmap information
NativeMethods.GetDIBits(hDC, hBitmap, 0, 0, null, ref bmi, (uint)ColorUsage.DIB_RGB_COLORS);
// Allocate the buffer for the bits
int imageSize = (int)bmi.bmiHeader.biSizeImage;
byte[] bits = new byte[imageSize];
// Get the actual bitmap data
if (NativeMethods.GetDIBits(hDC, hBitmap, 0, (uint)bmi.bmiHeader.biHeight, bits, ref bmi, (uint)ColorUsage.DIB_RGB_COLORS) == 0)
{
throw new Exception("Failed to get the bitmap bits.");
}
return bits;
}
finally
{
NativeMethods.SelectObject(hDC, hOldBitmap);
NativeMethods.DeleteDC(hDC);
}
}
public static IntPtr CF_BITMAP_Handle_FromRawData(byte[]? rawData)
{
if (rawData == null)
{
return IntPtr.Zero;
}
// Get the offset of bmBits in the BITMAP structure
int bmBitsOffset = Marshal.OffsetOf<BITMAP>("bmBits").ToInt32();
if (rawData.Length <= bmBitsOffset)
{
return IntPtr.Zero;
}
// Extract the BITMAP_HEADER from rawData
byte[] bitmapHeaderData = new byte[bmBitsOffset];
Array.Copy(rawData, 0, bitmapHeaderData, 0, bmBitsOffset);
_BitmapHeader bitmapHeader;
GCHandle headerHandle = GCHandle.Alloc(bitmapHeaderData, GCHandleType.Pinned);
try
{
bitmapHeader = Marshal.PtrToStructure<_BitmapHeader>(headerHandle.AddrOfPinnedObject());
}
finally
{
headerHandle.Free();
}
// Extract the bitmap bits from rawData
int bitsSize = rawData.Length - bmBitsOffset;
byte[] bitmapBits = new byte[bitsSize];
Array.Copy(rawData, bmBitsOffset, bitmapBits, 0, bitsSize);
// Calculate the stride (number of bytes per scanline)
int bytesPerPixel = (bitmapHeader.bmBitsPixel / 8);
int stride = bitmapHeader.bmWidth * bytesPerPixel;
// Adjust stride for padding to a multiple of 4 bytes
int padding = (4 - (stride % 4)) % 4;
int scanlineSize = stride + padding;
// Create a new array to hold the flipped bitmap bits. The bits are stored bottom-up, so we need to flip them or else it will be upside down.
byte[] flippedBitmapBits = new byte[bitmapBits.Length];
for (int y = 0; y < bitmapHeader.bmHeight; y++)
{
int sourceIndex = y * scanlineSize;
int destIndex = (bitmapHeader.bmHeight - 1 - y) * scanlineSize;
Array.Copy(bitmapBits, sourceIndex, flippedBitmapBits, destIndex, scanlineSize);
}
// Pin the flipped bitmap bits in memory
GCHandle bitsHandle = GCHandle.Alloc(flippedBitmapBits, GCHandleType.Pinned);
// Create the HBITMAP using the BITMAP_HEADER and flipped bitmap bits
IntPtr hBitmap = IntPtr.Zero;
try
{
hBitmap = NativeMethods.CreateBitmap(
bitmapHeader.bmWidth,
bitmapHeader.bmHeight,
bitmapHeader.bmPlanes,
bitmapHeader.bmBitsPixel,
bitsHandle.AddrOfPinnedObject()
);
}
finally
{
bitsHandle.Free();
}
return hBitmap;
}
public static byte[]? CF_BITMAP_RawData_FromHandle(IntPtr hBitmap)
{
if (hBitmap == IntPtr.Zero)
{
return null;
}
int bitmapSizeResult = NativeMethods.GetObject(hBitmap, 0, IntPtr.Zero); // Get the size of the BITMAP object
if (bitmapSizeResult == 0)
{
return null;
}
IntPtr pBitmap = Marshal.AllocHGlobal(bitmapSizeResult); // Allocate memory for GetObject to put BITMAP struct into
try
{
int result = NativeMethods.GetObject(hBitmap, bitmapSizeResult, pBitmap);
if (result == 0)
{
return null;
}
byte[] rawData = new byte[bitmapSizeResult];
Marshal.Copy(pBitmap, rawData, 0, bitmapSizeResult);
// Get the the pointer from the bits at the end of the BITMAP struct
if (Marshal.SizeOf(typeof(BITMAP)) <= bitmapSizeResult)
{
BITMAP bitmap = Marshal.PtrToStructure<BITMAP>(pBitmap);
// If the pointer is included in the struct, use that to get the actual bitmap data
if (bitmap.bmBits != IntPtr.Zero)
{
int bitsSize = (int)bitmap.bmWidthBytes * bitmap.bmHeight;
byte[] bits = new byte[bitsSize];
Marshal.Copy(bitmap.bmBits, bits, 0, bitsSize);
}
// Otherwise separately call GetDIBits to get the bitmap data and append to rawdata if received
else
{
byte[]? rawImageBitsOnly = FormatConverters.DIBits_From_HBitmap(hBitmap);
if (rawImageBitsOnly != null)
{
// Get the index of bmbits in the BITMAP struct
int bmBitsIndex = Marshal.OffsetOf<BITMAP>("bmBits").ToInt32();
// Copy the BITMAP struct to a new array
byte[] newRawData = new byte[bmBitsIndex + rawImageBitsOnly.Length];
Array.Copy(rawData, newRawData, bmBitsIndex);
Array.Copy(rawImageBitsOnly, 0, newRawData, bmBitsIndex, rawImageBitsOnly.Length);
rawData = newRawData;
//byte[] newRawData = new byte[rawData.Length + rawImageBitsOnly.Length];
//Array.Copy(rawData, newRawData, rawData.Length);
//Array.Copy(rawImageBitsOnly, 0, newRawData, rawData.Length, rawImageBitsOnly.Length);
//rawData = newRawData;
}
}
}
return rawData;
}
finally
{
Marshal.FreeHGlobal(pBitmap);
}
}
public static byte[]? CF_PALETTE_RawData_FromHandle(IntPtr hPalette)
{
if (hPalette == IntPtr.Zero)
{
return null;
}
try
{
IntPtr paletteEntryCountHandle = Marshal.AllocHGlobal(2);
try
{
int result = NativeMethods.GetObject(hPalette, 2, paletteEntryCountHandle);
if (result != 2)
{
return null;
}
ushort entryCount = (ushort)Marshal.ReadInt16(paletteEntryCountHandle);
int logPaletteHeaderSize = Marshal.SizeOf(typeof(_LogPaletteHeader)); // Size of palVersion and palNumEntries, doesn't change
int logPaletteSize = logPaletteHeaderSize + (Marshal.SizeOf<PALETTEENTRY>() * entryCount); // Subtract 1 because the standard LOGPALETTE struct already has one PALETTEENTRY
IntPtr pLogPalette = Marshal.AllocHGlobal(logPaletteSize);
try
{
Marshal.WriteInt16(pLogPalette, 0, 0x300); // palVersion
Marshal.WriteInt16(pLogPalette, 2, (short)entryCount); // palNumEntries
// For the last argument of GetPaletteEntries, point it to the start of the PALETTEENTRY array, not the entire handle
uint entriesRetrieved = NativeMethods.GetPaletteEntries(hPalette, 0, (uint)entryCount, pLogPalette + 4);
if (entriesRetrieved != entryCount)
{
return null;
}
byte[] rawData = new byte[logPaletteSize];
Marshal.Copy(pLogPalette, rawData, 0, logPaletteSize);
return rawData;
}
finally
{
Marshal.FreeHGlobal(pLogPalette);
}
}
catch(Exception ex)
{
Console.WriteLine($"Error in CF_PALETTE_RawData_FromHandle: {ex.Message}");
return null;
}
finally
{
Marshal.FreeHGlobal(paletteEntryCountHandle);
}
}
catch (Exception ex)
{
Console.WriteLine($"Error in CF_PALETTE_RawData_FromHandle: {ex.Message}");
return null;
}
}
public static IntPtr CF_PALETTE_Handle_FromRawData(byte[]? rawData)
{
if (rawData == null || rawData.Length < 4) // Ensure it's at least the size of the LOGPALETTE header info before the PALETTEENTRY array
{
return IntPtr.Zero;
}
int headerSize = Marshal.SizeOf<_LogPaletteHeader>();
// Determine the number of entries in the palette
ushort numEntries = BitConverter.ToUInt16(rawData, 2);
LOGPALETTE logPalette = new LOGPALETTE((ushort)numEntries);
int rawByteIndex = 4; // Skip the first 4 bytes, which are the palVersion and palNumEntries
for (int i = 0; i < numEntries; i++)
{
byte b1 = rawData[rawByteIndex];
byte b2 = rawData[rawByteIndex + 1];
byte b3 = rawData[rawByteIndex + 2];
byte b4 = rawData[rawByteIndex + 3];
rawByteIndex += 4;
logPalette.palPalEntry[i] = new PALETTEENTRY
{
peRed = b1,
peGreen = b2,
peBlue = b3,
peFlags = b4
};
}
// Marshal the LOGPALETTE struct to a handle
int entrySize = Marshal.SizeOf<PALETTEENTRY>();
int totalSize = headerSize + (entrySize * logPalette.palNumEntries);
IntPtr logPalettePtr = Marshal.AllocHGlobal(totalSize);
try
{
// Write palVersion and palNumEntries
Marshal.WriteInt16(logPalettePtr, 0, (short)logPalette.palVersion);
Marshal.WriteInt16(logPalettePtr, 2, (short)logPalette.palNumEntries);