打印自定义纸张大小

长江支流说的办法保留太多了,结果不行,很多类都是他在程序集里自定义的,源码又没公开

不过还是要感谢他的提示

今天和小陈搞了一天,他在国外的论坛上看到了一篇文章得到了启示,最后我们在凌晨3点终于把自定义纸张的代码给写出来了,看来必须用API,微软的.NET对打印的支持太菜了

现公开我们工作室实现此功能的部分代码

usingSystem;
usingSystem.Text;
usingSystem.Runtime.InteropServices;
usingSystem.Security;
usingSystem.ComponentModel;
usingSystem.Drawing.Printing;

namespaceMCCustomPrintForm
{
///<summary>
///成都微创工作室(电子科技大学微创工作室)
///Tell028-82853098
///Emailzyspipi@163.com,you680@gmail.com
///打印机纸张的真正自定义部分代码
///2006-1-2
///</summary>
publicclassMCCustomPrintForm
{
//Makeastaticclass
privateMCCustomPrintForm()
{
}

[StructLayout(LayoutKind.Sequential,CharSet=CharSet.Auto)]
internalstructstructPrinterDefaults
{
[MarshalAs(UnmanagedType.LPTStr)]publicStringpDatatype;
publicIntPtrpDevMode;
[MarshalAs(UnmanagedType.I4)]publicintDesiredAccess;
};

[DllImport("winspool.Drv",EntryPoint="OpenPrinter",SetLastError=true,
CharSet=CharSet.Unicode,ExactSpelling=false,CallingConvention=CallingConvention.StdCall),
SuppressUnmanagedCodeSecurityAttribute()]
internalstaticexternboolOpenPrinter([MarshalAs(UnmanagedType.LPTStr)]
stringprinterName,
outIntPtrphPrinter,
refstructPrinterDefaultspd);

[DllImport("winspool.Drv",EntryPoint="ClosePrinter",SetLastError=true,
CharSet=CharSet.Unicode,ExactSpelling=false,
CallingConvention=CallingConvention.StdCall),SuppressUnmanagedCodeSecurityAttribute()]
internalstaticexternboolClosePrinter(IntPtrphPrinter);

[StructLayout(LayoutKind.Sequential,CharSet=CharSet.Auto)]
internalstructstructSize
{
publicInt32width;
publicInt32height;
}

[StructLayout(LayoutKind.Sequential,CharSet=CharSet.Auto)]
internalstructstructRect
{
publicInt32left;
publicInt32top;
publicInt32right;
publicInt32bottom;
}

[StructLayout(LayoutKind.Explicit,CharSet=CharSet.Unicode)]
internalstructFormInfo1
{
[FieldOffset(0),MarshalAs(UnmanagedType.I4)]publicuintFlags;
[FieldOffset(4),MarshalAs(UnmanagedType.LPWStr)]publicStringpName;
[FieldOffset(8)]publicstructSizeSize;
[FieldOffset(16)]publicstructRectImageableArea;
};

[StructLayout(LayoutKind.Sequential,CharSet=CharSet.Ansi/*changedfromCharSet=CharSet.Auto*/)]
internalstructstructDevMode
{
[MarshalAs(UnmanagedType.ByValTStr,SizeConst=32)]publicString
dmDeviceName;
[MarshalAs(UnmanagedType.U2)]publicshortdmSpecVersion;
[MarshalAs(UnmanagedType.U2)]publicshortdmDriverVersion;
[MarshalAs(UnmanagedType.U2)]publicshortdmSize;
[MarshalAs(UnmanagedType.U2)]publicshortdmDriverExtra;
[MarshalAs(UnmanagedType.U4)]publicintdmFields;
[MarshalAs(UnmanagedType.I2)]publicshortdmOrientation;
[MarshalAs(UnmanagedType.I2)]publicshortdmPaperSize;
[MarshalAs(UnmanagedType.I2)]publicshortdmPaperLength;
[MarshalAs(UnmanagedType.I2)]publicshortdmPaperWidth;
[MarshalAs(UnmanagedType.I2)]publicshortdmScale;
[MarshalAs(UnmanagedType.I2)]publicshortdmCopies;
[MarshalAs(UnmanagedType.I2)]publicshortdmDefaultSource;
[MarshalAs(UnmanagedType.I2)]publicshortdmPrintQuality;
[MarshalAs(UnmanagedType.I2)]publicshortdmColor;
[MarshalAs(UnmanagedType.I2)]publicshortdmDuplex;
[MarshalAs(UnmanagedType.I2)]publicshortdmYResolution;
[MarshalAs(UnmanagedType.I2)]publicshortdmTTOption;
[MarshalAs(UnmanagedType.I2)]publicshortdmCollate;
[MarshalAs(UnmanagedType.ByValTStr,SizeConst=32)]publicStringdmFormName;
[MarshalAs(UnmanagedType.U2)]publicshortdmLogPixels;
[MarshalAs(UnmanagedType.U4)]publicintdmBitsPerPel;
[MarshalAs(UnmanagedType.U4)]publicintdmPelsWidth;
[MarshalAs(UnmanagedType.U4)]publicintdmPelsHeight;
[MarshalAs(UnmanagedType.U4)]publicintdmNup;
[MarshalAs(UnmanagedType.U4)]publicintdmDisplayFrequency;
[MarshalAs(UnmanagedType.U4)]publicintdmICMMethod;
[MarshalAs(UnmanagedType.U4)]publicintdmICMIntent;
[MarshalAs(UnmanagedType.U4)]publicintdmMediaType;
[MarshalAs(UnmanagedType.U4)]publicintdmDitherType;
[MarshalAs(UnmanagedType.U4)]publicintdmReserved1;
[MarshalAs(UnmanagedType.U4)]publicintdmReserved2;
}

[StructLayout(LayoutKind.Sequential,CharSet=CharSet.Auto)]
internalstructPRINTER_INFO_9
{
publicIntPtrpDevMode;
}

[DllImport("winspool.Drv",EntryPoint="AddFormW",SetLastError=true,
CharSet=CharSet.Unicode,ExactSpelling=true,
CallingConvention=CallingConvention.StdCall),SuppressUnmanagedCodeSecurityAttribute()]
internalstaticexternboolAddForm(
IntPtrphPrinter,
[MarshalAs(UnmanagedType.I4)]intlevel,
refFormInfo1form);

/*Thismethodisnotused
[DllImport("winspool.Drv",EntryPoint="SetForm",SetLastError=true,
CharSet=CharSet.Unicode,ExactSpelling=false,
CallingConvention=CallingConvention.StdCall),SuppressUnmanagedCodeSecurityAttribute()]
internalstaticexternboolSetForm(IntPtrphPrinter,stringpaperName,
[MarshalAs(UnmanagedType.I4)]intlevel,refFormInfo1form);
*/
[DllImport("winspool.Drv",EntryPoint="DeleteForm",SetLastError=true,
CharSet=CharSet.Unicode,ExactSpelling=false,CallingConvention=CallingConvention.StdCall),
SuppressUnmanagedCodeSecurityAttribute()]
internalstaticexternboolDeleteForm(
IntPtrphPrinter,
[MarshalAs(UnmanagedType.LPTStr)]stringpName);

[DllImport("kernel32.dll",EntryPoint="GetLastError",SetLastError=false,
ExactSpelling=true,CallingConvention=CallingConvention.StdCall),
SuppressUnmanagedCodeSecurityAttribute()]
internalstaticexternInt32GetLastError();

[DllImport("GDI32.dll",EntryPoint="CreateDC",SetLastError=true,
CharSet=CharSet.Unicode,ExactSpelling=false,
CallingConvention=CallingConvention.StdCall),
SuppressUnmanagedCodeSecurityAttribute()]
internalstaticexternIntPtrCreateDC([MarshalAs(UnmanagedType.LPTStr)]
stringpDrive,
[MarshalAs(UnmanagedType.LPTStr)]stringpName,
[MarshalAs(UnmanagedType.LPTStr)]stringpOutput,
refstructDevModepDevMode);

[DllImport("GDI32.dll",EntryPoint="ResetDC",SetLastError=true,
CharSet=CharSet.Unicode,ExactSpelling=false,
CallingConvention=CallingConvention.StdCall),
SuppressUnmanagedCodeSecurityAttribute()]
internalstaticexternIntPtrResetDC(
IntPtrhDC,
refstructDevMode
pDevMode);

[DllImport("GDI32.dll",EntryPoint="DeleteDC",SetLastError=true,
CharSet=CharSet.Unicode,ExactSpelling=false,
CallingConvention=CallingConvention.StdCall),
SuppressUnmanagedCodeSecurityAttribute()]
internalstaticexternboolDeleteDC(IntPtrhDC);

[DllImport("winspool.Drv",EntryPoint="SetPrinterA",SetLastError=true,
CharSet=CharSet.Auto,ExactSpelling=true,
CallingConvention=CallingConvention.StdCall),SuppressUnmanagedCodeSecurityAttribute()]
internalstaticexternboolSetPrinter(
IntPtrhPrinter,
[MarshalAs(UnmanagedType.I4)]intlevel,
IntPtrpPrinter,
[MarshalAs(UnmanagedType.I4)]intcommand);

/*
LONGDocumentProperties(
HWNDhWnd,//handletoparentwindow
HANDLEhPrinter,//handletoprinterobject
LPTSTRpDeviceName,//devicename
PDEVMODEpDevModeOutput,//modifieddevicemode
PDEVMODEpDevModeInput,//originaldevicemode
DWORDfMode//modeoptions
);
*/
[DllImport("winspool.Drv",EntryPoint="DocumentPropertiesA",SetLastError=true,
ExactSpelling=true,CallingConvention=CallingConvention.StdCall)]
publicstaticexternintDocumentProperties(
IntPtrhwnd,
IntPtrhPrinter,
[MarshalAs(UnmanagedType.LPStr)]stringpDeviceName/*changedfromStringtostring*/,
IntPtrpDevModeOutput,
IntPtrpDevModeInput,
intfMode
);

[DllImport("winspool.Drv",EntryPoint="GetPrinterA",SetLastError=true,
ExactSpelling=true,CallingConvention=CallingConvention.StdCall)]
publicstaticexternboolGetPrinter(
IntPtrhPrinter,
intdwLevel/*changedtypefromInt32*/,
IntPtrpPrinter,
intdwBuf/*chagnedfromInt32*/,
outintdwNeeded/*changedfromInt32*/
);

//SendMessageTimeouttools
[Flags]publicenumSendMessageTimeoutFlags:uint
{
SMTO_NORMAL=0x0000,
SMTO_BLOCK=0x0001,
SMTO_ABORTIFHUNG=0x0002,
SMTO_NOTIMEOUTIFNOTHUNG=0x0008
}
constintWM_SETTINGCHANGE=0x001A;
constintHWND_BROADCAST=0xffff;

[DllImport("user32.dll",SetLastError=true,CharSet=CharSet.Auto)]
publicstaticexternIntPtrSendMessageTimeout(
IntPtrwindowHandle,
uintMsg,
IntPtrwParam,
IntPtrlParam,
SendMessageTimeoutFlagsflags,
uinttimeout,
outIntPtrresult
);
//打印纸张长宽设置
publicstaticvoidAddMC80MmPaperSizeToDefaultPrinter()
{
AddCustomPaperSizeToDefaultPrinter("MC80mm*ReceiptLength",80.1f,4003.9f);
}

publicstaticvoidAddMC104MmPaperSizeToDefaultPrinter()
{
AddCustomPaperSizeToDefaultPrinter("MC104mm*ReceiptLength",104.1f,4003.9f);
}

///<summary>
///Addstheprinterformtothedefaultprinter
///</summary>
///<paramname="paperName">Nameoftheprinterform</param>
///<paramname="widthMm">Widthgiveninmillimeters</param>
///<paramname="heightMm">Heightgiveninmillimeters</param>
publicstaticvoidAddCustomPaperSizeToDefaultPrinter(stringpaperName,floatwidthMm,floatheightMm)
{
PrintDocumentpd=newPrintDocument();
stringsPrinterName=pd.PrinterSettings.PrinterName;
AddCustomPaperSize(sPrinterName,paperName,widthMm,heightMm);
}

///<summary>
///Addtheprinterformtoaprinter
///</summary>
///<paramname="printerName">Theprintername</param>
///<paramname="paperName">Nameoftheprinterform</param>
///<paramname="widthMm">Widthgiveninmillimeters</param>
///<paramname="heightMm">Heightgiveninmillimeters</param>
publicstaticvoidAddCustomPaperSize(stringprinterName,stringpaperName,float
widthMm,floatheightMm)
{
if(PlatformID.Win32NT==Environment.OSVersion.Platform)
{
//ThecodetoaddacustompapersizeisdifferentforWindowsNTthenitis
//forpreviousversionsofwindows

constintPRINTER_ACCESS_USE=0x00000008;
constintPRINTER_ACCESS_ADMINISTER=0x00000004;
constintFORM_PRINTER=0x00000002;

structPrinterDefaultsdefaults=newstructPrinterDefaults();
defaults.pDatatype=null;
defaults.pDevMode=IntPtr.Zero;
defaults.DesiredAccess=PRINTER_ACCESS_ADMINISTER|PRINTER_ACCESS_USE;

IntPtrhPrinter=IntPtr.Zero;

//Opentheprinter.
if(OpenPrinter(printerName,outhPrinter,refdefaults))
{
try
{
//deletetheformincaseitalreadyexists
DeleteForm(hPrinter,paperName);
//createandinitializetheFORM_INFO_1structure
FormInfo1formInfo=newFormInfo1();
formInfo.Flags=0;
formInfo.pName=paperName;
//allsizesin1000thsofmillimeters
formInfo.Size.width=(int)(widthMm*1000.0);
formInfo.Size.height=(int)(heightMm*1000.0);
formInfo.ImageableArea.left=0;
formInfo.ImageableArea.right=formInfo.Size.width;
formInfo.ImageableArea.top=0;
formInfo.ImageableArea.bottom=formInfo.Size.height;
if(!AddForm(hPrinter,1,refformInfo))
{
StringBuilderstrBuilder=newStringBuilder();
strBuilder.AppendFormat("Failedtoaddthecustompapersize{0}totheprinter{1},Systemerrornumber:{2}",
paperName,printerName,GetLastError());
thrownewApplicationException(strBuilder.ToString());
}

//INIT
constintDM_OUT_BUFFER=2;
constintDM_IN_BUFFER=8;
structDevModedevMode=newstructDevMode();
IntPtrhPrinterInfo,hDummy;
PRINTER_INFO_9printerInfo;
printerInfo.pDevMode=IntPtr.Zero;
intiPrinterInfoSize,iDummyInt;


//GETTHESIZEOFTHEDEV_MODEBUFFER
intiDevModeSize=DocumentProperties(IntPtr.Zero,hPrinter,printerName,IntPtr.Zero,IntPtr.Zero,0);

if(iDevModeSize<0)
thrownewApplicationException("CannotgetthesizeoftheDEVMODEstructure.");

//ALLOCATETHEBUFFER
IntPtrhDevMode=Marshal.AllocCoTaskMem(iDevModeSize+100);

//GETAPOINTERTOTHEDEV_MODEBUFFER
intiRet=DocumentProperties(IntPtr.Zero,hPrinter,printerName,hDevMode,IntPtr.Zero,DM_OUT_BUFFER);

if(iRet<0)
thrownewApplicationException("CannotgettheDEVMODEstructure.");

//FILLTHEDEV_MODESTRUCTURE
devMode=(structDevMode)Marshal.PtrToStructure(hDevMode,devMode.GetType());

//SETTHEFORMNAMEFIELDSTOINDICATETHATTHISFIELDWILLBEMODIFIED
devMode.dmFields=0x10000;//DM_FORMNAME
//SETTHEFORMNAME
devMode.dmFormName=paperName;

//PUTTHEDEV_MODESTRUCTUREBACKINTOTHEPOINTER
Marshal.StructureToPtr(devMode,hDevMode,true);

//MERGETHENEWCHAGESWITHTHEOLD
iRet=DocumentProperties(IntPtr.Zero,hPrinter,printerName,
printerInfo.pDevMode,printerInfo.pDevMode,DM_IN_BUFFER|DM_OUT_BUFFER);

if(iRet<0)
thrownewApplicationException("Unabletosettheorientationsettingforthisprinter.");

//GETTHEPRINTERINFOSIZE
GetPrinter(hPrinter,9,IntPtr.Zero,0,outiPrinterInfoSize);
if(iPrinterInfoSize==0)
thrownewApplicationException("GetPrinterfailed.Couldn'tgetthe#bytesneededforsharedPRINTER_INFO_9structure");

//ALLOCATETHEBUFFER
hPrinterInfo=Marshal.AllocCoTaskMem(iPrinterInfoSize+100);

//GETAPOINTERTOTHEPRINTERINFOBUFFER
boolbSuccess=GetPrinter(hPrinter,9,hPrinterInfo,iPrinterInfoSize,outiDummyInt);

if(!bSuccess)
thrownewApplicationException("GetPrinterfailed.Couldn'tgetthesharedPRINTER_INFO_9structure");

//FILLTHEPRINTERINFOSTRUCTURE
printerInfo=(PRINTER_INFO_9)Marshal.PtrToStructure(hPrinterInfo,printerInfo.GetType());
printerInfo.pDevMode=hDevMode;

//GETAPOINTERTOTHEPRINTERINFOSTRUCTURE
Marshal.StructureToPtr(printerInfo,hPrinterInfo,true);

//SETTHEPRINTERSETTINGS
bSuccess=SetPrinter(hPrinter,9,hPrinterInfo,0);

if(!bSuccess)
thrownewWin32Exception(Marshal.GetLastWin32Error(),"SetPrinter()failed.Couldn'tsettheprintersettings");

//Tellallopenprogramsthatthischangeoccurred.
SendMessageTimeout(
newIntPtr(HWND_BROADCAST),
WM_SETTINGCHANGE,
IntPtr.Zero,
IntPtr.Zero,
MCCustomPrintForm.SendMessageTimeoutFlags.SMTO_NORMAL,
1000,
outhDummy);
}
finally
{
ClosePrinter(hPrinter);
}
}
else
{
StringBuilderstrBuilder=newStringBuilder();
strBuilder.AppendFormat("Failedtoopenthe{0}printer,Systemerrornumber:{1}",
printerName,GetLastError());
thrownewApplicationException(strBuilder.ToString());
}
}
else
{
structDevModepDevMode=newstructDevMode();
IntPtrhDC=CreateDC(null,printerName,null,refpDevMode);
if(hDC!=IntPtr.Zero)
{
constlongDM_PAPERSIZE=0x00000002L;
constlongDM_PAPERLENGTH=0x00000004L;
constlongDM_PAPERWIDTH=0x00000008L;
pDevMode.dmFields=(int)(DM_PAPERSIZE|DM_PAPERWIDTH|DM_PAPERLENGTH);
pDevMode.dmPaperSize=256;
pDevMode.dmPaperWidth=(short)(widthMm*1000.0);
pDevMode.dmPaperLength=(short)(heightMm*1000.0);
ResetDC(hDC,refpDevMode);
DeleteDC(hDC);
}
}
}
}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值