紧急求助,C#自定义纸张问题.
IntPtr pi = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(StructDevMode)));
if (pi == IntPtr.Zero)
return;
try
{
settings.CopyToHdevmode(pi);
StructDevMode devmode = (StructDevMode)Marshal.PtrToStructure(pi, typeof(StructDevMode));
devmode.dmSize = (short)Marshal.SizeOf(typeof(StructDevMode));
devmode.dmPaperSize = 0x100;
devmode.dmPaperWidth = (short)(size.Width * 10); // 以0.1mm为单位的宽度
devmode.dmPaperLength = (short)(size.Height * 10); // 以0.1mm为单位的高度
devmode.dmFields = 14; // DM_PAPERSIZE | DM_PAPERLENGTH | DM_PAPERWIDTH;
Marshal.StructureToPtr(devmode, pi, false);
settings.SetHdevmode(pi);
}
catch { }
finally
{
Marshal.FreeHGlobal(pi);
}
这段代码经常报表"内存无效的错误",导致程序自动退出.无法Catch,有哪位大侠能帮我.
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
internal struct StructDevMode
{
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)]
public String dmDeviceName;
[MarshalAs(UnmanagedType.U2)]
public short dmSpecVersion;
[MarshalAs(UnmanagedType.U2)]
public short dmDriverVersion;
[MarshalAs(UnmanagedType.U2)]
public short dmSize;
[MarshalAs(UnmanagedType.U2)]
public short dmDriverExtra;
[MarshalAs(UnmanagedType.U4)]
public int dmFields;
[MarshalAs(UnmanagedType.I2)]
public short dmOrientation;
[MarshalAs(UnmanagedType.I2)]
public short dmPaperSize;
[MarshalAs(UnmanagedType.I2)]
public short dmPaperLength;
[MarshalAs(UnmanagedType.I2)]
public short dmPaperWidth;
[MarshalAs(UnmanagedType.I2)]
public short dmScale;
[MarshalAs(UnmanagedType.I2)]
public short dmCopies;
[MarshalAs(UnmanagedType.I2)]
public short dmDefaultSource;
[MarshalAs(UnmanagedType.I2)]
public short dmPrintQuality;
[MarshalAs(UnmanagedType.I2)]
public short dmColor;
[MarshalAs(UnmanagedType.I2)]
public short dmDuplex;
[MarshalAs(UnmanagedType.I2)]
public short dmYResolution;
[MarshalAs(UnmanagedType.I2)]
public short dmTTOption;
[MarshalAs(UnmanagedType.I2)]
public short dmCollate;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)]
public String dmFormName;
[MarshalAs(UnmanagedType.U2)]
public short dmLogPixels;
[MarshalAs(UnmanagedType.U4)]
public int dmBitsPerPel;
[MarshalAs(UnmanagedType.U4)]
public int dmPelsWidth;
[MarshalAs(UnmanagedType.U4)]
public int dmPelsHeight;
[MarshalAs(UnmanagedTy