-
Notifications
You must be signed in to change notification settings - Fork 5.5k
Expand file tree
/
Copy pathPrinterSettings.cs
More file actions
1646 lines (1438 loc) · 58.8 KB
/
Copy pathPrinterSettings.cs
File metadata and controls
1646 lines (1438 loc) · 58.8 KB
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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Collections;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing.Imaging;
using System.Drawing.Internal;
using System.Globalization;
using System.IO;
using System.Runtime.InteropServices;
namespace System.Drawing.Printing
{
/// <summary>
/// Information about how a document should be printed, including which printer to print it on.
/// </summary>
public class PrinterSettings : ICloneable
{
// All read/write data is stored in managed code, and whenever we need to call Win32,
// we create new DEVMODE and DEVNAMES structures. We don't store device capabilities,
// though.
//
// Also, all properties have hidden tri-state logic -- yes/no/default
private const int Padding64Bit = 4;
private string? _printerName; // default printer.
private string _driverName = "";
private string _outputPort = "";
private bool _printToFile;
// Whether the PrintDialog has been shown (not whether it's currently shown). This is how we enforce SafePrinting.
private bool _printDialogDisplayed;
private short _extrabytes;
private byte[]? _extrainfo;
private short _copies = -1;
private Duplex _duplex = System.Drawing.Printing.Duplex.Default;
private TriState _collate = TriState.Default;
private readonly PageSettings _defaultPageSettings;
private int _fromPage;
private int _toPage;
private int _maxPage = 9999;
private int _minPage;
private PrintRange _printRange;
private short _devmodebytes;
private byte[]? _cachedDevmode;
/// <summary>
/// Initializes a new instance of the <see cref='PrinterSettings'/> class.
/// </summary>
public PrinterSettings()
{
_defaultPageSettings = new PageSettings(this);
}
/// <summary>
/// Gets a value indicating whether the printer supports duplex (double-sided) printing.
/// </summary>
public bool CanDuplex
{
get { return DeviceCapabilities(SafeNativeMethods.DC_DUPLEX, IntPtr.Zero, 0) == 1; }
}
/// <summary>
/// Gets or sets the number of copies to print.
/// </summary>
public short Copies
{
get
{
if (_copies != -1)
return _copies;
else
return GetModeField(ModeField.Copies, 1);
}
set
{
if (value < 0)
throw new ArgumentException(SR.Format(SR.InvalidLowBoundArgumentEx,
nameof(value), value.ToString(CultureInfo.CurrentCulture),
(0).ToString(CultureInfo.CurrentCulture)));
/*
We shouldnt allow copies to be set since the copies can be a large number
and can be reflected in PrintDialog. So for the Copies property,
we prefer that for SafePrinting, copied cannot be set programmatically
but through the print dialog.
Any lower security could set copies to anything.
*/
_copies = value;
}
}
/// <summary>
/// Gets or sets a value indicating whether the print out is collated.
/// </summary>
public bool Collate
{
get
{
if (!_collate.IsDefault)
return (bool)_collate;
else
return GetModeField(ModeField.Collate, SafeNativeMethods.DMCOLLATE_FALSE) == SafeNativeMethods.DMCOLLATE_TRUE;
}
set { _collate = value; }
}
/// <summary>
/// Gets the default page settings for this printer.
/// </summary>
public PageSettings DefaultPageSettings
{
get { return _defaultPageSettings; }
}
// As far as I can tell, Windows no longer pays attention to driver names and output ports.
// But I'm leaving this code in place in case I'm wrong.
internal string DriverName
{
get { return _driverName; }
}
/// <summary>
/// Gets or sets the printer's duplex setting.
/// </summary>
public Duplex Duplex
{
get
{
if (_duplex != Duplex.Default)
{
return _duplex;
}
return (Duplex)GetModeField(ModeField.Duplex, SafeNativeMethods.DMDUP_SIMPLEX);
}
set
{
if (value < Duplex.Default || value > Duplex.Horizontal)
{
throw new InvalidEnumArgumentException(nameof(value), unchecked((int)value), typeof(Duplex));
}
_duplex = value;
}
}
/// <summary>
/// Gets or sets the first page to print.
/// </summary>
public int FromPage
{
get { return _fromPage; }
set
{
if (value < 0)
throw new ArgumentException(SR.Format(SR.InvalidLowBoundArgumentEx,
nameof(value), value.ToString(CultureInfo.CurrentCulture),
(0).ToString(CultureInfo.CurrentCulture)));
_fromPage = value;
}
}
/// <summary>
/// Gets the names of all printers installed on the machine.
/// </summary>
public static StringCollection InstalledPrinters
{
get
{
int sizeofstruct;
// Note: The call to get the size of the buffer required for level 5 does not work properly on NT platforms.
const int Level = 4;
// PRINTER_INFO_4 is 12 or 24 bytes in size depending on the architecture.
if (IntPtr.Size == 8)
{
sizeofstruct = (IntPtr.Size * 2) + (sizeof(int) * 1) + Padding64Bit;
}
else
{
sizeofstruct = (IntPtr.Size * 2) + (sizeof(int) * 1);
}
int bufferSize;
int count;
Interop.Winspool.EnumPrinters(SafeNativeMethods.PRINTER_ENUM_LOCAL | SafeNativeMethods.PRINTER_ENUM_CONNECTIONS, null, Level, IntPtr.Zero, 0, out bufferSize, out _);
IntPtr buffer = Marshal.AllocCoTaskMem(bufferSize);
int returnCode = Interop.Winspool.EnumPrinters(SafeNativeMethods.PRINTER_ENUM_LOCAL | SafeNativeMethods.PRINTER_ENUM_CONNECTIONS,
null, Level, buffer,
bufferSize, out _, out count);
var array = new string[count];
if (returnCode == 0)
{
Marshal.FreeCoTaskMem(buffer);
throw new Win32Exception();
}
for (int i = 0; i < count; i++)
{
// The printer name is at offset 0
//
IntPtr namePointer = (IntPtr)Marshal.ReadIntPtr((IntPtr)(checked((long)buffer + i * sizeofstruct)));
array[i] = Marshal.PtrToStringAuto(namePointer)!;
}
Marshal.FreeCoTaskMem(buffer);
return new StringCollection(array);
}
}
/// <summary>
/// Gets a value indicating whether the <see cref='PrinterName'/> property designates the default printer.
/// </summary>
public bool IsDefaultPrinter
{
get
{
return (_printerName == null || _printerName == GetDefaultPrinterName());
}
}
/// <summary>
/// Gets a value indicating whether the printer is a plotter, as opposed to a raster printer.
/// </summary>
public bool IsPlotter
{
get
{
return GetDeviceCaps(Interop.Gdi32.DeviceCapability.TECHNOLOGY, Interop.Gdi32.DeviceTechnology.DT_RASPRINTER) == Interop.Gdi32.DeviceTechnology.DT_PLOTTER;
}
}
/// <summary>
/// Gets a value indicating whether the <see cref='PrinterName'/> property designates a valid printer.
/// </summary>
public bool IsValid
{
get
{
return DeviceCapabilities(SafeNativeMethods.DC_COPIES, IntPtr.Zero, -1) != -1;
}
}
/// <summary>
/// Gets the angle, in degrees, which the portrait orientation is rotated to produce the landscape orientation.
/// </summary>
public int LandscapeAngle
{
get { return DeviceCapabilities(SafeNativeMethods.DC_ORIENTATION, IntPtr.Zero, 0); }
}
/// <summary>
/// Gets the maximum number of copies allowed by the printer.
/// </summary>
public int MaximumCopies
{
get { return DeviceCapabilities(SafeNativeMethods.DC_COPIES, IntPtr.Zero, 1); }
}
/// <summary>
/// Gets or sets the highest <see cref='FromPage'/> or <see cref='ToPage'/> which may be selected in a print dialog box.
/// </summary>
public int MaximumPage
{
get { return _maxPage; }
set
{
if (value < 0)
throw new ArgumentException(SR.Format(SR.InvalidLowBoundArgumentEx,
nameof(value), value.ToString(CultureInfo.CurrentCulture),
(0).ToString(CultureInfo.CurrentCulture)));
_maxPage = value;
}
}
/// <summary>
/// Gets or sets the lowest <see cref='FromPage'/> or <see cref='ToPage'/> which may be selected in a print dialog box.
/// </summary>
public int MinimumPage
{
get { return _minPage; }
set
{
if (value < 0)
throw new ArgumentException(SR.Format(SR.InvalidLowBoundArgumentEx,
nameof(value), value.ToString(CultureInfo.CurrentCulture),
(0).ToString(CultureInfo.CurrentCulture)));
_minPage = value;
}
}
internal string OutputPort
{
get
{
return _outputPort;
}
set
{
_outputPort = value;
}
}
/// <summary>
/// Indicates the name of the printerfile.
/// </summary>
public string PrintFileName
{
get
{
string printFileName = OutputPort;
return printFileName;
}
set
{
if (string.IsNullOrEmpty(value))
{
throw new ArgumentNullException(value);
}
OutputPort = value;
}
}
/// <summary>
/// Gets the paper sizes supported by this printer.
/// </summary>
public PaperSizeCollection PaperSizes
{
get { return new PaperSizeCollection(Get_PaperSizes()); }
}
/// <summary>
/// Gets the paper sources available on this printer.
/// </summary>
public PaperSourceCollection PaperSources
{
get { return new PaperSourceCollection(Get_PaperSources()); }
}
/// <summary>
/// Whether the print dialog has been displayed. In SafePrinting mode, a print dialog is required to print.
/// After printing, this property is set to false if the program does not have AllPrinting; this guarantees
/// a document is only printed once each time the print dialog is shown.
/// </summary>
internal bool PrintDialogDisplayed
{
get
{
return _printDialogDisplayed;
}
set
{
_printDialogDisplayed = value;
}
}
/// <summary>
/// Gets or sets the pages the user has asked to print.
/// </summary>
public PrintRange PrintRange
{
get { return _printRange; }
set
{
if (!Enum.IsDefined(typeof(PrintRange), value))
throw new InvalidEnumArgumentException(nameof(value), unchecked((int)value), typeof(PrintRange));
_printRange = value;
}
}
/// <summary>
/// Indicates whether to print to a file instead of a port.
/// </summary>
public bool PrintToFile
{
get
{
return _printToFile;
}
set
{
_printToFile = value;
}
}
/// <summary>
/// Gets or sets the name of the printer.
/// </summary>
public string PrinterName
{
get
{
return PrinterNameInternal;
}
set
{
PrinterNameInternal = value;
}
}
private string PrinterNameInternal
{
get
{
if (_printerName == null)
return GetDefaultPrinterName();
else
return _printerName;
}
set
{
// Reset the DevMode and Extrabytes...
_cachedDevmode = null;
_extrainfo = null;
_printerName = value;
// PrinterName can be set through a fulltrusted assembly without using the PrintDialog.
// So dont set this variable here.
//PrintDialogDisplayed = true;
}
}
/// <summary>
/// Gets the resolutions supported by this printer.
/// </summary>
public PrinterResolutionCollection PrinterResolutions
{
get { return new PrinterResolutionCollection(Get_PrinterResolutions()); }
}
/// <summary>
/// If the image is a JPEG or a PNG (Image.RawFormat) and the printer returns true from
/// ExtEscape(CHECKJPEGFORMAT) or ExtEscape(CHECKPNGFORMAT) then this function returns true.
/// </summary>
public bool IsDirectPrintingSupported(ImageFormat imageFormat)
{
bool isDirectPrintingSupported = false;
if (imageFormat.Equals(ImageFormat.Jpeg) || imageFormat.Equals(ImageFormat.Png))
{
int nEscape = imageFormat.Equals(ImageFormat.Jpeg) ? Interop.Gdi32.CHECKJPEGFORMAT : Interop.Gdi32.CHECKPNGFORMAT;
int outData;
DeviceContext dc = CreateInformationContext(DefaultPageSettings);
HandleRef hdc = new HandleRef(dc, dc.Hdc);
try
{
isDirectPrintingSupported = Interop.Gdi32.ExtEscape(hdc, Interop.Gdi32.QUERYESCSUPPORT, sizeof(int), ref nEscape, 0, out outData) > 0;
}
finally
{
dc.Dispose();
}
}
return isDirectPrintingSupported;
}
/// <summary>
/// This method utilizes the CHECKJPEGFORMAT/CHECKPNGFORMAT printer escape functions
/// to determine whether the printer can handle a JPEG image.
///
/// If the image is a JPEG or a PNG (Image.RawFormat) and the printer returns true
/// from ExtEscape(CHECKJPEGFORMAT) or ExtEscape(CHECKPNGFORMAT) then this function returns true.
/// </summary>
public bool IsDirectPrintingSupported(Image image)
{
bool isDirectPrintingSupported = false;
if (image.RawFormat.Equals(ImageFormat.Jpeg) || image.RawFormat.Equals(ImageFormat.Png))
{
MemoryStream stream = new MemoryStream();
try
{
image.Save(stream, image.RawFormat);
byte[] pvImage = stream.ToArray();
int nEscape = image.RawFormat.Equals(ImageFormat.Jpeg) ? Interop.Gdi32.CHECKJPEGFORMAT : Interop.Gdi32.CHECKPNGFORMAT;
int outData = 0;
DeviceContext dc = CreateInformationContext(DefaultPageSettings);
HandleRef hdc = new HandleRef(dc, dc.Hdc);
try
{
bool querySupported = Interop.Gdi32.ExtEscape(hdc, Interop.Gdi32.QUERYESCSUPPORT, sizeof(int), ref nEscape, 0, out outData) > 0;
if (querySupported)
{
isDirectPrintingSupported = (Interop.Gdi32.ExtEscape(hdc, nEscape, pvImage.Length, pvImage, sizeof(int), out outData) > 0)
&& (outData == 1);
}
}
finally
{
dc.Dispose();
}
}
finally
{
stream.Close();
}
}
return isDirectPrintingSupported;
}
/// <summary>
/// Gets a value indicating whether the printer supports color printing.
/// </summary>
public bool SupportsColor
{
get
{
// If the printer supports color printing, the return value is 1; otherwise, the return value is zero.
// The pointerToBuffer parameter is not used.
return DeviceCapabilities(
capability: SafeNativeMethods.DC_COLORDEVICE,
pointerToBuffer: IntPtr.Zero,
defaultValue: 0) == 1;
}
}
/// <summary>
/// Gets or sets the last page to print.
/// </summary>
public int ToPage
{
get { return _toPage; }
set
{
if (value < 0)
throw new ArgumentException(SR.Format(SR.InvalidLowBoundArgumentEx,
nameof(value), value.ToString(CultureInfo.CurrentCulture),
(0).ToString(CultureInfo.CurrentCulture)));
_toPage = value;
}
}
/// <summary>
/// Creates an identical copy of this object.
/// </summary>
public object Clone()
{
PrinterSettings clone = (PrinterSettings)MemberwiseClone();
clone._printDialogDisplayed = false;
return clone;
}
// what is done in copytohdevmode cannot give unwanted access AllPrinting permission
internal DeviceContext CreateDeviceContext(PageSettings pageSettings)
{
IntPtr modeHandle = GetHdevmodeInternal();
DeviceContext? dc = null;
try
{
//Copy the PageSettings to the DEVMODE...
pageSettings.CopyToHdevmode(modeHandle);
dc = CreateDeviceContext(modeHandle);
}
finally
{
Interop.Kernel32.GlobalFree(modeHandle);
}
return dc;
}
internal DeviceContext CreateDeviceContext(IntPtr hdevmode)
{
IntPtr modePointer = Interop.Kernel32.GlobalLock(hdevmode);
DeviceContext dc = DeviceContext.CreateDC(DriverName, PrinterNameInternal, fileName:null, modePointer);
Interop.Kernel32.GlobalUnlock(hdevmode);
return dc;
}
// A read-only DC, which is faster than CreateHdc
// what is done in copytohdevmode cannot give unwanted access AllPrinting permission
internal DeviceContext CreateInformationContext(PageSettings pageSettings)
{
IntPtr modeHandle = GetHdevmodeInternal();
DeviceContext dc;
try
{
//Copy the PageSettings to the DEVMODE...
pageSettings.CopyToHdevmode(modeHandle);
dc = CreateInformationContext(modeHandle);
}
finally
{
Interop.Kernel32.GlobalFree(modeHandle);
}
return dc;
}
// A read-only DC, which is faster than CreateHdc
internal DeviceContext CreateInformationContext(IntPtr hdevmode)
{
IntPtr modePointer = Interop.Kernel32.GlobalLock(hdevmode);
DeviceContext dc = DeviceContext.CreateIC(DriverName, PrinterNameInternal, fileName:null, modePointer);
Interop.Kernel32.GlobalUnlock(hdevmode);
return dc;
}
public Graphics CreateMeasurementGraphics()
{
return CreateMeasurementGraphics(DefaultPageSettings);
}
//whatever the call stack calling HardMarginX and HardMarginY here is safe
public Graphics CreateMeasurementGraphics(bool honorOriginAtMargins)
{
Graphics g = CreateMeasurementGraphics();
if (honorOriginAtMargins)
{
g.TranslateTransform(-_defaultPageSettings.HardMarginX, -_defaultPageSettings.HardMarginY);
g.TranslateTransform(_defaultPageSettings.Margins.Left, _defaultPageSettings.Margins.Top);
}
return g;
}
public Graphics CreateMeasurementGraphics(PageSettings pageSettings)
{
// returns the Graphics object for the printer
DeviceContext dc = CreateDeviceContext(pageSettings);
Graphics g = Graphics.FromHdcInternal(dc.Hdc);
g.PrintingHelper = dc; // Graphics will dispose of the DeviceContext.
return g;
}
//whatever the call stack calling HardMarginX and HardMarginY here is safe
public Graphics CreateMeasurementGraphics(PageSettings pageSettings, bool honorOriginAtMargins)
{
Graphics g = CreateMeasurementGraphics();
if (honorOriginAtMargins)
{
g.TranslateTransform(-pageSettings.HardMarginX, -pageSettings.HardMarginY);
g.TranslateTransform(pageSettings.Margins.Left, pageSettings.Margins.Top);
}
return g;
}
// Create a PRINTDLG with a few useful defaults.
// Try to keep this consistent with PrintDialog.CreatePRINTDLG.
private static unsafe void CreatePRINTDLGX86(out Interop.Comdlg32.PRINTDLGX86 data)
{
data = default;
data.lStructSize = sizeof(Interop.Comdlg32.PRINTDLGX86);
data.nFromPage = 1;
data.nToPage = 1;
data.nMinPage = 0;
data.nMaxPage = 9999;
data.nCopies = 1;
}
// Create a PRINTDLG with a few useful defaults.
// Try to keep this consistent with PrintDialog.CreatePRINTDLG.
private static unsafe void CreatePRINTDLG(out Interop.Comdlg32.PRINTDLG data)
{
data = default;
data.lStructSize = sizeof(Interop.Comdlg32.PRINTDLG);
data.nFromPage = 1;
data.nToPage = 1;
data.nMinPage = 0;
data.nMaxPage = 9999;
data.nCopies = 1;
}
// Use FastDeviceCapabilities where possible -- computing PrinterName is quite slow
private int DeviceCapabilities(short capability, IntPtr pointerToBuffer, int defaultValue)
{
string printerName = PrinterName;
return FastDeviceCapabilities(capability, pointerToBuffer, defaultValue, printerName);
}
// We pass PrinterName in as a parameter rather than computing it ourselves because it's expensive to compute.
// We need to pass IntPtr.Zero since passing HDevMode is non-performant.
private static int FastDeviceCapabilities(short capability, IntPtr pointerToBuffer, int defaultValue, string printerName)
{
int result = Interop.Winspool.DeviceCapabilities(printerName, GetOutputPort(),
capability, pointerToBuffer, IntPtr.Zero);
if (result == -1)
return defaultValue;
return result;
}
// Called by get_PrinterName
private static string GetDefaultPrinterName()
{
if (IntPtr.Size == 8)
{
CreatePRINTDLG(out Interop.Comdlg32.PRINTDLG data);
data.Flags = SafeNativeMethods.PD_RETURNDEFAULT;
bool status = Interop.Comdlg32.PrintDlg(ref data);
if (!status)
return SR.NoDefaultPrinter;
IntPtr handle = data.hDevNames;
IntPtr names = Interop.Kernel32.GlobalLock(handle);
if (names == IntPtr.Zero)
throw new Win32Exception();
string name = ReadOneDEVNAME(names, 1);
Interop.Kernel32.GlobalUnlock(handle);
// Windows allocates them, but we have to free them
Interop.Kernel32.GlobalFree(data.hDevNames);
Interop.Kernel32.GlobalFree(data.hDevMode);
return name;
}
else
{
CreatePRINTDLGX86(out Interop.Comdlg32.PRINTDLGX86 data);
data.Flags = SafeNativeMethods.PD_RETURNDEFAULT;
bool status = Interop.Comdlg32.PrintDlg(ref data);
if (!status)
return SR.NoDefaultPrinter;
IntPtr handle = data.hDevNames;
IntPtr names = Interop.Kernel32.GlobalLock(handle);
if (names == IntPtr.Zero)
throw new Win32Exception();
string name = ReadOneDEVNAME(names, 1);
Interop.Kernel32.GlobalUnlock(handle);
// Windows allocates them, but we have to free them
Interop.Kernel32.GlobalFree(data.hDevNames);
Interop.Kernel32.GlobalFree(data.hDevMode);
return name;
}
}
// Called by get_OutputPort
private static string GetOutputPort()
{
if (IntPtr.Size == 8)
{
CreatePRINTDLG(out Interop.Comdlg32.PRINTDLG data);
data.Flags = SafeNativeMethods.PD_RETURNDEFAULT;
bool status = Interop.Comdlg32.PrintDlg(ref data);
if (!status)
return SR.NoDefaultPrinter;
IntPtr handle = data.hDevNames;
IntPtr names = Interop.Kernel32.GlobalLock(handle);
if (names == IntPtr.Zero)
throw new Win32Exception();
string name = ReadOneDEVNAME(names, 2);
Interop.Kernel32.GlobalUnlock(handle);
// Windows allocates them, but we have to free them
Interop.Kernel32.GlobalFree(data.hDevNames);
Interop.Kernel32.GlobalFree(data.hDevMode);
return name;
}
else
{
CreatePRINTDLGX86(out Interop.Comdlg32.PRINTDLGX86 data);
data.Flags = SafeNativeMethods.PD_RETURNDEFAULT;
bool status = Interop.Comdlg32.PrintDlg(ref data);
if (!status)
return SR.NoDefaultPrinter;
IntPtr handle = data.hDevNames;
IntPtr names = Interop.Kernel32.GlobalLock(handle);
if (names == IntPtr.Zero)
throw new Win32Exception();
string name = ReadOneDEVNAME(names, 2);
Interop.Kernel32.GlobalUnlock(handle);
// Windows allocates them, but we have to free them
Interop.Kernel32.GlobalFree(data.hDevNames);
Interop.Kernel32.GlobalFree(data.hDevMode);
return name;
}
}
private int GetDeviceCaps(Interop.Gdi32.DeviceCapability capability, int defaultValue)
{
using (DeviceContext dc = CreateInformationContext(DefaultPageSettings))
{
return Interop.Gdi32.GetDeviceCaps(new HandleRef(dc, dc.Hdc), capability);
}
}
/// <summary>
/// Creates a handle to a DEVMODE structure which correspond too the printer settings.When you are done with the
/// handle, you must deallocate it yourself:
/// Interop.Kernel32.GlobalFree(handle);
/// Where "handle" is the return value from this method.
/// </summary>
public IntPtr GetHdevmode()
{
IntPtr modeHandle = GetHdevmodeInternal();
_defaultPageSettings.CopyToHdevmode(modeHandle);
return modeHandle;
}
internal IntPtr GetHdevmodeInternal()
{
// getting the printer name is quite expensive if PrinterName is left default,
// because it needs to figure out what the default printer is
return GetHdevmodeInternal(PrinterNameInternal);
}
private IntPtr GetHdevmodeInternal(string printer)
{
// Create DEVMODE
int modeSize = Interop.Winspool.DocumentProperties(NativeMethods.NullHandleRef, NativeMethods.NullHandleRef, printer, IntPtr.Zero, NativeMethods.NullHandleRef, 0);
if (modeSize < 1)
{
throw new InvalidPrinterException(this);
}
IntPtr handle = Interop.Kernel32.GlobalAlloc(SafeNativeMethods.GMEM_MOVEABLE, (uint)modeSize); // cannot be <0 anyway
IntPtr pointer = Interop.Kernel32.GlobalLock(handle);
//Get the DevMode only if its not cached....
if (_cachedDevmode != null)
{
Marshal.Copy(_cachedDevmode, 0, pointer, _devmodebytes);
}
else
{
int returnCode = Interop.Winspool.DocumentProperties(NativeMethods.NullHandleRef, NativeMethods.NullHandleRef, printer, pointer, NativeMethods.NullHandleRef, SafeNativeMethods.DM_OUT_BUFFER);
if (returnCode < 0)
{
throw new Win32Exception();
}
}
Interop.Gdi32.DEVMODE mode = Marshal.PtrToStructure<Interop.Gdi32.DEVMODE>(pointer)!;
if (_extrainfo != null)
{
// guard against buffer overrun attacks (since design allows client to set a new printer name without updating the devmode)
// by checking for a large enough buffer size before copying the extrainfo buffer
if (_extrabytes <= mode.dmDriverExtra)
{
IntPtr pointeroffset = (IntPtr)(checked((long)pointer + (long)mode.dmSize));
Marshal.Copy(_extrainfo, 0, pointeroffset, _extrabytes);
}
}
if ((mode.dmFields & SafeNativeMethods.DM_COPIES) == SafeNativeMethods.DM_COPIES)
{
if (_copies != -1)
mode.dmCopies = _copies;
}
if ((mode.dmFields & SafeNativeMethods.DM_DUPLEX) == SafeNativeMethods.DM_DUPLEX)
{
if (unchecked((int)_duplex) != -1)
mode.dmDuplex = unchecked((short)_duplex);
}
if ((mode.dmFields & SafeNativeMethods.DM_COLLATE) == SafeNativeMethods.DM_COLLATE)
{
if (_collate.IsNotDefault)
mode.dmCollate = (short)(((bool)_collate) ? SafeNativeMethods.DMCOLLATE_TRUE : SafeNativeMethods.DMCOLLATE_FALSE);
}
Marshal.StructureToPtr(mode, pointer, false);
int retCode = Interop.Winspool.DocumentProperties(NativeMethods.NullHandleRef, NativeMethods.NullHandleRef, printer, pointer, pointer, SafeNativeMethods.DM_IN_BUFFER | SafeNativeMethods.DM_OUT_BUFFER);
if (retCode < 0)
{
Interop.Kernel32.GlobalFree(handle);
Interop.Kernel32.GlobalUnlock(handle);
return IntPtr.Zero;
}
Interop.Kernel32.GlobalUnlock(handle);
return handle;
}
/// <summary>
/// Creates a handle to a DEVMODE structure which correspond to the printer and page settings.
/// When you are done with the handle, you must deallocate it yourself:
/// Interop.Kernel32.GlobalFree(handle);
/// Where "handle" is the return value from this method.
/// </summary>
public IntPtr GetHdevmode(PageSettings pageSettings)
{
IntPtr modeHandle = GetHdevmodeInternal();
pageSettings.CopyToHdevmode(modeHandle);
return modeHandle;
}
/// <summary>
/// Creates a handle to a DEVNAMES structure which correspond to the printer settings.
/// When you are done with the handle, you must deallocate it yourself:
/// Interop.Kernel32.GlobalFree(handle);
/// Where "handle" is the return value from this method.
/// </summary>
public IntPtr GetHdevnames()
{
string printerName = PrinterName; // the PrinterName property is slow when using the default printer
string driver = DriverName; // make sure we are writing out exactly the same string as we got the length of
string outPort = OutputPort;
// Create DEVNAMES structure
// +4 for null terminator
int namesCharacters = checked(4 + printerName.Length + driver.Length + outPort.Length);
// 8 = size of fixed portion of DEVNAMES
short offset = (short)(8 / Marshal.SystemDefaultCharSize); // Offsets are in characters, not bytes
uint namesSize = (uint)checked(Marshal.SystemDefaultCharSize * (offset + namesCharacters)); // always >0
IntPtr handle = Interop.Kernel32.GlobalAlloc(SafeNativeMethods.GMEM_MOVEABLE | SafeNativeMethods.GMEM_ZEROINIT, namesSize);
IntPtr namesPointer = Interop.Kernel32.GlobalLock(handle);
Marshal.WriteInt16(namesPointer, offset); // wDriverOffset
offset += WriteOneDEVNAME(driver, namesPointer, offset);
Marshal.WriteInt16((IntPtr)(checked((long)namesPointer + 2)), offset); // wDeviceOffset
offset += WriteOneDEVNAME(printerName, namesPointer, offset);
Marshal.WriteInt16((IntPtr)(checked((long)namesPointer + 4)), offset); // wOutputOffset
offset += WriteOneDEVNAME(outPort, namesPointer, offset);
Marshal.WriteInt16((IntPtr)(checked((long)namesPointer + 6)), offset); // wDefault
Interop.Kernel32.GlobalUnlock(handle);
return handle;
}
// Handles creating then disposing a default DEVMODE
internal short GetModeField(ModeField field, short defaultValue)
{
return GetModeField(field, defaultValue, IntPtr.Zero);
}
internal short GetModeField(ModeField field, short defaultValue, IntPtr modeHandle)
{
bool ownHandle = false;
short result;
try
{
if (modeHandle == IntPtr.Zero)
{
try
{
modeHandle = GetHdevmodeInternal();
ownHandle = true;
}
catch (InvalidPrinterException)
{
return defaultValue;
}
}
IntPtr modePointer = Interop.Kernel32.GlobalLock(new HandleRef(this, modeHandle));
Interop.Gdi32.DEVMODE mode = Marshal.PtrToStructure<Interop.Gdi32.DEVMODE>(modePointer)!;
switch (field)
{
case ModeField.Orientation:
result = mode.dmOrientation;
break;
case ModeField.PaperSize:
result = mode.dmPaperSize;
break;
case ModeField.PaperLength:
result = mode.dmPaperLength;
break;
case ModeField.PaperWidth:
result = mode.dmPaperWidth;
break;
case ModeField.Copies:
result = mode.dmCopies;
break;
case ModeField.DefaultSource:
result = mode.dmDefaultSource;
break;
case ModeField.PrintQuality:
result = mode.dmPrintQuality;
break;
case ModeField.Color:
result = mode.dmColor;
break;
case ModeField.Duplex:
result = mode.dmDuplex;
break;
case ModeField.YResolution:
result = mode.dmYResolution;
break;
case ModeField.TTOption: