zoukankan      html  css  js  c++  java
  • C#如何实现Windows自带打印功能

    C#如何实现Windows自带打印功能

    2017-10-29 12:52:34 王啸tr1912 阅读数 18822 文章标签: windows打印 更多

    分类专栏: C# 项目经验

    版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。

    本文链接:https://blog.csdn.net/tr1912/article/details/78384711

            接着上回说,在使用打印机自带的SDK开发失利只后,经过一系列的实验,发现,这个打印机可以直接用我安装好的驱动直接进行打印操作,用word直接调整好字体之后打印是完全没有问题的,所以,推测,应该可以直接调用人家封装好的一些驱动进行打印,但是要怎么连接这些驱动呢?

    一、打印控件

            首先我们要提到的就是在C#中的一个关于打印的控件了,叫:PrintDocument,说他是一个控件,其实也就是一个关于windows打印的属性和代码的集合而已,但是结合着windows自带的一些对话框窗体,我们可以轻而易举的做一个打印的小程序。

            我们要做的是,首先建立一个窗体,然后从工具箱中找到PrintDocument这个控件,然后添加上就可以了,可以看到控件的属性是这样的:

            并没有什么特殊的地方,但是在方法里面却有一个很重要的方法,那就是他的printPage这个方法,这个就是每次触发这个控件的打印的内容核心,先贴上如下代码:

    
     
    1. private void pd1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)

    2. {

    3. Graphics g = e.Graphics; //获得绘图对象

    4. float linesPerPage = 0; //页面的行号

    5. float yPosition = 0; //绘制字符串的纵向位置

    6. int count = 0; //行计数器

    7. float leftMargin = 1; //左边距

    8. float topMargin = 1; //上边距

    9. string line = ""; //行字符串

    10. Font printFont = this.textBox1.Font; //当前的打印字体

    11. SolidBrush myBrush = new SolidBrush(Color.Black);//刷子

    12. linesPerPage = e.MarginBounds.Height / printFont.GetHeight(g);//每页可打印的行数

    13. //逐行的循环打印一页

    14. while (count < linesPerPage && ((line = lineReader.ReadLine()) != null))

    15. {

    16. yPosition = topMargin + (count * printFont.GetHeight(g));

    17. g.DrawString(line, printFont, myBrush, leftMargin, yPosition, new StringFormat());

    18. count++;

    19. }

    20. // 注意:使用本段代码前,要在该窗体的类中定义lineReader对象:

    21. // StringReader lineReader = null;

    22. //如果本页打印完成而line不为空,说明还有没完成的页面,这将触发下一次的打印事件。在下一次的打印中lineReader会

    23. //自动读取上次没有打印完的内容,因为lineReader是这个打印方法外的类的成员,它可以记录当前读取的位置

    24. if (line != null)

    25. e.HasMorePages = true;

    26. else

    27. {

    28. e.HasMorePages = false;

    29. // 重新初始化lineReader对象,不然使用打印预览中的打印按钮打印出来是空白页

    30. lineReader = new StringReader(textBox1.Text); // textBox是你要打印的文本框的内容

    31. }

    32. }


            这里需要注意的是,使用了lineReader这个类的对象,这个对象的特点就是可以把对象中赋值的字符串按照行(以\r\n为准的换行)来进行字符串的获取,上面代码中的line就是指的获得的一行的数据。我们用system.draw的Graphics里面的绘图对象来进行基本的字符绘图,最后把绘图对象打印到我们纸上,就是这个打印里面的内容。

            所以,我们这个里面需要引入的一个引用就是using System.Drawing.Printing;   这样整个控件加代码就可以运行了,说明一下,这个打印的调用需要触发,使用的是如下代码:

    
     
    1. lineReader = new StringReader(stb.ToString()); // 获取要打印的字符串

    2.  
    3. pd1.Print(); //执行打印方法


            另外说明一下,这里执行的时候,有一些辅助设置,比如打印预览,打印机使用的默认的,还有页面的配置等都是有专门的对话框,我把他们都放在了菜单里面,如图:

    下面我们来说一下他们的实现,其实很是简单:

    打印设置:

    
     
    1. private void FileMenuItem_PrintSet_Click(object sender, EventArgs e)

    2. {

    3. PrintDialog printDialog = new PrintDialog();

    4. printDialog.Document = pd1;

    5. printDialog.ShowDialog();

    6.  
    7. }

    页面设置:

    
     
    1. private void FileMenuItem_PageSet_Click(object sender, EventArgs e)

    2. {

    3. PageSetupDialog pageSetupDialog = new PageSetupDialog();

    4. pageSetupDialog.Document = pd1;

    5. pageSetupDialog.ShowDialog();

    6. }

    打印预览:

    
     
    1. private void FileMenuItem_PrintView_Click(object sender, EventArgs e)

    2. {

    3. PrintPreviewDialog printPreviewDialog = new PrintPreviewDialog();

    4. printPreviewDialog.Document = pd1;

    5. lineReader = new StringReader(stb.ToString());

    6. try

    7. {

    8. printPreviewDialog.ShowDialog();

    9. }

    10. catch(Exception excep)

    11. {

    12. MessageBox.Show(excep.Message, "打印出错", MessageBoxButtons.OK, MessageBoxIcon.Error);

    13. }

    14. }



         这些页面里面的设置在选择保存的时候会自动存储到Graphic对象当中,因此,可以配置之后使用。

    二、系统API接口

            既然有系统定制的控件,那么系统的接入API肯定也少不了,不过,我目前从网络上找到的只有一小部分而已,并且都是一些获取配置,设置默认等一些列的代码,在此分享给大家

    
     
    1. using System;

    2. using System.Text;

    3. using System.Runtime.InteropServices;

    4. using System.Security;

    5. using System.ComponentModel;

    6. using System.IO;

    7.  
    8. namespace WindowsFormsApplication1

    9. {

    10. public class PrinterHelper

    11. {

    12. private PrinterHelper(){ }

    13. #region API声明

    14. [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]

    15. internal struct structPrinterDefaults

    16. {

    17. [MarshalAs(UnmanagedType.LPTStr)]

    18. public String pDatatype;

    19. public IntPtr pDevMode;

    20. [MarshalAs(UnmanagedType.I4)]

    21. public int DesiredAccess;

    22. };

    23. [DllImport("winspool.Drv", EntryPoint = "OpenPrinter", SetLastError = true,CharSet = CharSet.Unicode, ExactSpelling = false, CallingConvention = CallingConvention.StdCall),

    24. SuppressUnmanagedCodeSecurityAttribute()]

    25. internal static extern bool OpenPrinter([MarshalAs(UnmanagedType.LPTStr)] string printerName,out IntPtr phPrinter,ref structPrinterDefaults pd);

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

    28. internal static extern bool ClosePrinter(IntPtr phPrinter);

    29.  
    30. [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]

    31. internal struct structSize

    32. {

    33. public Int32 width;

    34. public Int32 height;

    35. }

    36.  
    37. [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]

    38. internal struct structRect

    39. {

    40. public Int32 left;

    41. public Int32 top;

    42. public Int32 right;

    43. public Int32 bottom;

    44. }

    45.  
    46. [StructLayout(LayoutKind.Explicit, CharSet = CharSet.Unicode)]

    47. internal struct FormInfo1

    48. {

    49. [FieldOffset(0), MarshalAs(UnmanagedType.I4)]

    50. public uint Flags;

    51. [FieldOffset(4), MarshalAs(UnmanagedType.LPWStr)]

    52. public String pName;

    53. [FieldOffset(8)]

    54. public structSize Size;

    55. [FieldOffset(16)]

    56. public structRect ImageableArea;

    57. };

    58.  
    59. [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]

    60. internal struct structDevMode

    61. {

    62. [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)]

    63. public String

    64. dmDeviceName;

    65. [MarshalAs(UnmanagedType.U2)]

    66. public short dmSpecVersion;

    67. [MarshalAs(UnmanagedType.U2)]

    68. public short dmDriverVersion;

    69. [MarshalAs(UnmanagedType.U2)]

    70. public short dmSize;

    71. [MarshalAs(UnmanagedType.U2)]

    72. public short dmDriverExtra;

    73. [MarshalAs(UnmanagedType.U4)]

    74. public int dmFields;

    75. [MarshalAs(UnmanagedType.I2)]

    76. public short dmOrientation;

    77. [MarshalAs(UnmanagedType.I2)]

    78. public short dmPaperSize;

    79. [MarshalAs(UnmanagedType.I2)]

    80. public short dmPaperLength;

    81. [MarshalAs(UnmanagedType.I2)]

    82. public short dmPaperWidth;

    83. [MarshalAs(UnmanagedType.I2)]

    84. public short dmScale;

    85. [MarshalAs(UnmanagedType.I2)]

    86. public short dmCopies;

    87. [MarshalAs(UnmanagedType.I2)]

    88. public short dmDefaultSource;

    89. [MarshalAs(UnmanagedType.I2)]

    90. public short dmPrintQuality;

    91. [MarshalAs(UnmanagedType.I2)]

    92. public short dmColor;

    93. [MarshalAs(UnmanagedType.I2)]

    94. public short dmDuplex;

    95. [MarshalAs(UnmanagedType.I2)]

    96. public short dmYResolution;

    97. [MarshalAs(UnmanagedType.I2)]

    98. public short dmTTOption;

    99. [MarshalAs(UnmanagedType.I2)]

    100. public short dmCollate;

    101. [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)]

    102. public String dmFormName;

    103. [MarshalAs(UnmanagedType.U2)]

    104. public short dmLogPixels;

    105. [MarshalAs(UnmanagedType.U4)]

    106. public int dmBitsPerPel;

    107. [MarshalAs(UnmanagedType.U4)]

    108. public int dmPelsWidth;

    109. [MarshalAs(UnmanagedType.U4)]

    110. public int dmPelsHeight;

    111. [MarshalAs(UnmanagedType.U4)]

    112. public int dmNup;

    113. [MarshalAs(UnmanagedType.U4)]

    114. public int dmDisplayFrequency;

    115. [MarshalAs(UnmanagedType.U4)]

    116. public int dmICMMethod;

    117. [MarshalAs(UnmanagedType.U4)]

    118. public int dmICMIntent;

    119. [MarshalAs(UnmanagedType.U4)]

    120. public int dmMediaType;

    121. [MarshalAs(UnmanagedType.U4)]

    122. public int dmDitherType;

    123. [MarshalAs(UnmanagedType.U4)]

    124. public int dmReserved1;

    125. [MarshalAs(UnmanagedType.U4)]

    126. public int dmReserved2;

    127. }

    128.  
    129. [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]

    130. internal struct PRINTER_INFO_9

    131. {

    132. public IntPtr pDevMode;

    133. }

    134.  
    135. [DllImport("winspool.Drv", EntryPoint = "AddFormW", SetLastError = true,CharSet = CharSet.Unicode, ExactSpelling = true,

    136. CallingConvention = CallingConvention.StdCall), SuppressUnmanagedCodeSecurityAttribute()]

    137. internal static extern bool AddForm(IntPtr phPrinter,[MarshalAs(UnmanagedType.I4)] int level,ref FormInfo1 form);

    138.  
    139. [DllImport("winspool.Drv", EntryPoint = "DeleteForm", SetLastError = true,CharSet = CharSet.Unicode, ExactSpelling = false, CallingConvention = CallingConvention.StdCall),

    140. SuppressUnmanagedCodeSecurityAttribute()]

    141. internal static extern bool DeleteForm(IntPtr phPrinter,[MarshalAs(UnmanagedType.LPTStr)] string pName);

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

    144. internal static extern Int32 GetLastError();

    145.  
    146. [DllImport("GDI32.dll", EntryPoint = "CreateDC", SetLastError = true,CharSet = CharSet.Unicode, ExactSpelling = false,CallingConvention = CallingConvention.StdCall),SuppressUnmanagedCodeSecurityAttribute()]

    147. internal static extern IntPtr CreateDC([MarshalAs(UnmanagedType.LPTStr)] string pDrive,[MarshalAs(UnmanagedType.LPTStr)] string pName,[MarshalAs(UnmanagedType.LPTStr)] string pOutput,ref structDevMode pDevMode);

    148.  
    149. [DllImport("GDI32.dll", EntryPoint = "ResetDC", SetLastError = true,

    150. CharSet = CharSet.Unicode, ExactSpelling = false,CallingConvention = CallingConvention.StdCall),SuppressUnmanagedCodeSecurityAttribute()]

    151. internal static extern IntPtr ResetDC(IntPtr hDC,ref structDevMode pDevMode);

    152.  
    153. [DllImport("GDI32.dll", EntryPoint = "DeleteDC", SetLastError = true, CharSet = CharSet.Unicode, ExactSpelling = false,

    154. CallingConvention = CallingConvention.StdCall),SuppressUnmanagedCodeSecurityAttribute()]

    155. internal static extern bool DeleteDC(IntPtr hDC);

    156.  
    157. [DllImport("winspool.Drv", EntryPoint = "SetPrinterA", SetLastError = true,

    158. CharSet = CharSet.Auto, ExactSpelling = true,CallingConvention = CallingConvention.StdCall), SuppressUnmanagedCodeSecurityAttribute()]

    159. internal static extern bool SetPrinter(IntPtr hPrinter,[MarshalAs(UnmanagedType.I4)] int level,IntPtr pPrinter,[MarshalAs(UnmanagedType.I4)] int command);

    160.  
    161. [DllImport("winspool.Drv", EntryPoint = "DocumentPropertiesA", SetLastError = true,ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]

    162. internal static extern int DocumentProperties(IntPtr hwnd,IntPtr hPrinter,[MarshalAs(UnmanagedType.LPStr)] string pDeviceName,IntPtr pDevModeOutput,IntPtr pDevModeInput,int fMode);

    163.  
    164. [DllImport("winspool.Drv", EntryPoint = "GetPrinterA", SetLastError = true,ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]

    165. internal static extern bool GetPrinter(IntPtr hPrinter,int dwLevel,IntPtr pPrinter,int dwBuf,out int dwNeeded);

    166.  
    167. [Flags]

    168. internal enum SendMessageTimeoutFlags : uint

    169. {

    170. SMTO_NORMAL = 0x0000,

    171. SMTO_BLOCK = 0x0001,

    172. SMTO_ABORTIFHUNG = 0x0002,

    173. SMTO_NOTIMEOUTIFNOTHUNG = 0x0008

    174. }

    175. const int WM_SETTINGCHANGE = 0x001A;

    176. const int HWND_BROADCAST = 0xffff;

    177.  
    178. [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]

    179. internal static extern IntPtr SendMessageTimeout(IntPtr windowHandle,uint Msg,IntPtr wParam,IntPtr lParam,SendMessageTimeoutFlags flags,uint timeout,out IntPtr result);

    180.  
    181. //EnumPrinters用到的函数和结构体

    182. [DllImport("winspool.drv", CharSet = CharSet.Auto, SetLastError = true)]

    183. private static extern bool EnumPrinters(PrinterEnumFlags Flags, string Name, uint Level,IntPtr pPrinterEnum, uint cbBuf,ref uint pcbNeeded, ref uint pcReturned);

    184.  
    185. [StructLayout(LayoutKind.Sequential)]

    186. internal struct PRINTER_INFO_2

    187. {

    188. public string pServerName;

    189. public string pPrinterName;

    190. public string pShareName;

    191. public string pPortName;

    192. public string pDriverName;

    193. public string pComment;

    194. public string pLocation;

    195. public IntPtr pDevMode;

    196. public string pSepFile;

    197. public string pPrintProcessor;

    198. public string pDatatype;

    199. public string pParameters;

    200. public IntPtr pSecurityDescriptor;

    201. public uint Attributes;

    202. public uint Priority;

    203. public uint DefaultPriority;

    204. public uint StartTime;

    205. public uint UntilTime;

    206. public uint Status;

    207. public uint cJobs;

    208. public uint AveragePPM;

    209. }

    210.  
    211. [FlagsAttribute]

    212. internal enum PrinterEnumFlags

    213. {

    214. PRINTER_ENUM_DEFAULT = 0x00000001,

    215. PRINTER_ENUM_LOCAL = 0x00000002,

    216. PRINTER_ENUM_CONNECTIONS = 0x00000004,

    217. PRINTER_ENUM_FAVORITE = 0x00000004,

    218. PRINTER_ENUM_NAME = 0x00000008,

    219. PRINTER_ENUM_REMOTE = 0x00000010,

    220. PRINTER_ENUM_SHARED = 0x00000020,

    221. PRINTER_ENUM_NETWORK = 0x00000040,

    222. PRINTER_ENUM_EXPAND = 0x00004000,

    223. PRINTER_ENUM_CONTAINER = 0x00008000,

    224. PRINTER_ENUM_ICONMASK = 0x00ff0000,

    225. PRINTER_ENUM_ICON1 = 0x00010000,

    226. PRINTER_ENUM_ICON2 = 0x00020000,

    227. PRINTER_ENUM_ICON3 = 0x00040000,

    228. PRINTER_ENUM_ICON4 = 0x00080000,

    229. PRINTER_ENUM_ICON5 = 0x00100000,

    230. PRINTER_ENUM_ICON6 = 0x00200000,

    231. PRINTER_ENUM_ICON7 = 0x00400000,

    232. PRINTER_ENUM_ICON8 = 0x00800000,

    233. PRINTER_ENUM_HIDE = 0x01000000

    234. }

    235.  
    236. //打印机状态

    237. [FlagsAttribute]

    238. internal enum PrinterStatus

    239. {

    240. PRINTER_STATUS_BUSY = 0x00000200,

    241. PRINTER_STATUS_DOOR_OPEN = 0x00400000,

    242. PRINTER_STATUS_ERROR = 0x00000002,

    243. PRINTER_STATUS_INITIALIZING = 0x00008000,

    244. PRINTER_STATUS_IO_ACTIVE = 0x00000100,

    245. PRINTER_STATUS_MANUAL_FEED = 0x00000020,

    246. PRINTER_STATUS_NO_TONER = 0x00040000,

    247. PRINTER_STATUS_NOT_AVAILABLE = 0x00001000,

    248. PRINTER_STATUS_OFFLINE = 0x00000080,

    249. PRINTER_STATUS_OUT_OF_MEMORY = 0x00200000,

    250. PRINTER_STATUS_OUTPUT_BIN_FULL = 0x00000800,

    251. PRINTER_STATUS_PAGE_PUNT = 0x00080000,

    252. PRINTER_STATUS_PAPER_JAM = 0x00000008,

    253. PRINTER_STATUS_PAPER_OUT = 0x00000010,

    254. PRINTER_STATUS_PAPER_PROBLEM = 0x00000040,

    255. PRINTER_STATUS_PAUSED = 0x00000001,

    256. PRINTER_STATUS_PENDING_DELETION = 0x00000004,

    257. PRINTER_STATUS_PRINTING = 0x00000400,

    258. PRINTER_STATUS_PROCESSING = 0x00004000,

    259. PRINTER_STATUS_TONER_LOW = 0x00020000,

    260. PRINTER_STATUS_USER_INTERVENTION = 0x00100000,

    261. PRINTER_STATUS_WAITING = 0x20000000,

    262. PRINTER_STATUS_WARMING_UP = 0x00010000

    263. }

    264.  
    265. //GetDefaultPrinter用到的API函数说明

    266. [DllImport("winspool.drv", CharSet = CharSet.Auto, SetLastError = true)]

    267. internal static extern bool GetDefaultPrinter(StringBuilder pszBuffer, ref int size);

    268.  
    269. //SetDefaultPrinter用到的API函数声明

    270. [DllImport("winspool.drv", CharSet = CharSet.Auto, SetLastError = true)]

    271. internal static extern bool SetDefaultPrinter(string Name);

    272.  
    273. //EnumFormsA用到的函数声明,应该和EnumPrinters类似

    274. [DllImport("winspool.drv", EntryPoint = "EnumForms")]

    275. internal static extern int EnumFormsA(IntPtr hPrinter, int Level, ref byte pForm, int cbBuf, ref int pcbNeeded, ref int pcReturned);

    276.  
    277. #endregion API声明

    278. internal static int GetPrinterStatusInt(string PrinterName)

    279. {

    280. int intRet = 0;

    281. IntPtr hPrinter;

    282. structPrinterDefaults defaults = new structPrinterDefaults();

    283. if (OpenPrinter(PrinterName, out hPrinter, ref defaults))

    284. {

    285. int cbNeeded = 0;

    286. bool bolRet = GetPrinter(hPrinter, 2, IntPtr.Zero, 0, out cbNeeded);

    287. if (cbNeeded > 0)

    288. {

    289. IntPtr pAddr = Marshal.AllocHGlobal((int)cbNeeded);

    290. bolRet = GetPrinter(hPrinter, 2, pAddr, cbNeeded, out cbNeeded);

    291. if (bolRet)

    292. {

    293. PRINTER_INFO_2 Info2 = new PRINTER_INFO_2();

    294.  
    295. Info2 = (PRINTER_INFO_2)Marshal.PtrToStructure(pAddr, typeof(PRINTER_INFO_2));

    296.  
    297. intRet = System.Convert.ToInt32(Info2.Status);

    298. }

    299. Marshal.FreeHGlobal(pAddr);

    300. }

    301. ClosePrinter(hPrinter);

    302. }

    303. return intRet;

    304. }

    305. internal static PRINTER_INFO_2[] EnumPrintersByFlag(PrinterEnumFlags Flags)

    306. {

    307. uint cbNeeded = 0;

    308. uint cReturned = 0;

    309. bool ret = EnumPrinters(PrinterEnumFlags.PRINTER_ENUM_LOCAL, null, 2, IntPtr.Zero, 0, ref cbNeeded, ref cReturned);

    310. IntPtr pAddr = Marshal.AllocHGlobal((int)cbNeeded);

    311. ret = EnumPrinters(PrinterEnumFlags.PRINTER_ENUM_LOCAL, null, 2, pAddr, cbNeeded, ref cbNeeded, ref cReturned);

    312. if (ret)

    313. {

    314. PRINTER_INFO_2[] Info2 = new PRINTER_INFO_2[cReturned];

    315. int offset = pAddr.ToInt32();

    316. for (int i = 0; i < cReturned; i++)

    317. {

    318. Info2[i].pServerName = Marshal.PtrToStringAuto(Marshal.ReadIntPtr(new IntPtr(offset)));

    319. offset += 4;

    320. Info2[i].pPrinterName = Marshal.PtrToStringAuto(Marshal.ReadIntPtr(new IntPtr(offset)));

    321. offset += 4;

    322. Info2[i].pShareName = Marshal.PtrToStringAuto(Marshal.ReadIntPtr(new IntPtr(offset)));

    323. offset += 4;

    324. Info2[i].pPortName = Marshal.PtrToStringAuto(Marshal.ReadIntPtr(new IntPtr(offset)));

    325. offset += 4;

    326. Info2[i].pDriverName = Marshal.PtrToStringAuto(Marshal.ReadIntPtr(new IntPtr(offset)));

    327. offset += 4;

    328. Info2[i].pComment = Marshal.PtrToStringAuto(Marshal.ReadIntPtr(new IntPtr(offset)));

    329. offset += 4;

    330. Info2[i].pLocation = Marshal.PtrToStringAuto(Marshal.ReadIntPtr(new IntPtr(offset)));

    331. offset += 4;

    332. Info2[i].pDevMode = Marshal.ReadIntPtr(new IntPtr(offset));

    333. offset += 4;

    334. Info2[i].pSepFile = Marshal.PtrToStringAuto(Marshal.ReadIntPtr(new IntPtr(offset)));

    335. offset += 4;

    336. Info2[i].pPrintProcessor = Marshal.PtrToStringAuto(Marshal.ReadIntPtr(new IntPtr(offset)));

    337. offset += 4;

    338. Info2[i].pDatatype = Marshal.PtrToStringAuto(Marshal.ReadIntPtr(new IntPtr(offset)));

    339. offset += 4;

    340. Info2[i].pParameters = Marshal.PtrToStringAuto(Marshal.ReadIntPtr(new IntPtr(offset)));

    341. offset += 4;

    342. Info2[i].pSecurityDescriptor = Marshal.ReadIntPtr(new IntPtr(offset));

    343. offset += 4;

    344. Info2[i].Attributes = (uint)Marshal.ReadIntPtr(new IntPtr(offset));

    345. offset += 4;

    346. Info2[i].Priority = (uint)Marshal.ReadInt32(new IntPtr(offset));

    347. offset += 4;

    348. Info2[i].DefaultPriority = (uint)Marshal.ReadInt32(new IntPtr(offset));

    349. offset += 4;

    350. Info2[i].StartTime = (uint)Marshal.ReadInt32(new IntPtr(offset));

    351. offset += 4;

    352. Info2[i].UntilTime = (uint)Marshal.ReadInt32(new IntPtr(offset));

    353. offset += 4;

    354. Info2[i].Status = (uint)Marshal.ReadInt32(new IntPtr(offset));

    355. offset += 4;

    356. Info2[i].cJobs = (uint)Marshal.ReadInt32(new IntPtr(offset));

    357. offset += 4;

    358. Info2[i].AveragePPM = (uint)Marshal.ReadInt32(new IntPtr(offset));

    359. offset += 4;

    360. }

    361. Marshal.FreeHGlobal(pAddr);

    362. return Info2;

    363. }

    364. else

    365. {

    366. return new PRINTER_INFO_2[0];

    367. }

    368. }

    369. #region 获取当前指定打印机的状态

    370. /// </summary>

    371. /// 获取当前指定打印机的状态

    372. /// </summary>

    373. /// <param name="PrinterName">打印机名称</param>

    374. /// <returns>打印机状态描述</returns>

    375.  
    376. public static string GetPrinterStatus(string PrinterName)

    377. {

    378. int intValue = GetPrinterStatusInt(PrinterName);

    379. string strRet = string.Empty;

    380. switch (intValue)

    381. {

    382. case 0:

    383. strRet = "准备就绪(Ready)";

    384. break;

    385. case 0x00000200:

    386. strRet = "忙(Busy)";

    387. break;

    388. case 0x00400000:

    389. strRet = "门被打开(Printer Door Open)";

    390. break;

    391. case 0x00000002:

    392. strRet = "错误(Printer Error)";

    393. break;

    394. case 0x0008000:

    395. strRet = "正在初始化(Initializing)";

    396. break;

    397. case 0x00000100:

    398. strRet = "正在输入或输出(I/O Active)";

    399. break;

    400. case 0x00000020:

    401. strRet = "手工送纸(Manual Feed)";

    402. break;

    403. case 0x00040000:

    404. strRet = "无墨粉(No Toner)";

    405. break;

    406. case 0x00001000:

    407. strRet = "不可用(Not Available)";

    408. break;

    409. case 0x00000080:

    410. strRet = "脱机(Off Line)";

    411. break;

    412. case 0x00200000:

    413. strRet = "内存溢出(Out of Memory)";

    414. break;

    415. case 0x00000800:

    416. strRet = "输出口已满(Output Bin Full)";

    417. break;

    418. case 0x00080000:

    419. strRet = "当前页无法打印(Page Punt)";

    420. break;

    421. case 0x00000008:

    422. strRet = "塞纸(Paper Jam)";

    423. break;

    424. case 0x00000010:

    425. strRet = "打印纸用完(Paper Out)";

    426. break;

    427. case 0x00000040:

    428. strRet = "纸张问题(Page Problem)";

    429. break;

    430. case 0x00000001:

    431. strRet = "暂停(Paused)";

    432. break;

    433. case 0x00000004:

    434. strRet = "正在删除(Pending Deletion)";

    435. break;

    436. case 0x00000400:

    437. strRet = "正在打印(Printing)";

    438. break;

    439. case 0x00004000:

    440. strRet = "正在处理(Processing)";

    441. break;

    442. case 0x00020000:

    443. strRet = "墨粉不足(Toner Low)";

    444. break;

    445. case 0x00100000:

    446. strRet = "需要用户干预(User Intervention)";

    447. break;

    448. case 0x20000000:

    449. strRet = "等待(Waiting)";

    450. break;

    451. case 0x00010000:

    452. strRet = "正在准备(Warming Up)";

    453. break;

    454. default:

    455. strRet = "未知状态(Unknown Status)";

    456. break;

    457. }

    458. return strRet;

    459. }

    460. #endregion 获取当前指定打印机的状态

    461. #region 删除已经存在的自定义纸张

    462. /**/

    463. /// <summary>

    464. /// 删除已经存在的自定义纸张

    465. /// </summary>

    466. /// <param name="PrinterName">打印机名称</param>

    467. /// <param name="PaperName">纸张名称</param>

    468. public static void DeleteCustomPaperSize(string PrinterName, string PaperName)

    469. {

    470. const int PRINTER_ACCESS_USE = 0x00000008;

    471. const int PRINTER_ACCESS_ADMINISTER = 0x00000004;

    472.  
    473. structPrinterDefaults defaults = new structPrinterDefaults();

    474. defaults.pDatatype = null;

    475. defaults.pDevMode = IntPtr.Zero;

    476. defaults.DesiredAccess = PRINTER_ACCESS_ADMINISTER | PRINTER_ACCESS_USE;

    477.  
    478. IntPtr hPrinter = IntPtr.Zero;

    479.  
    480. //打开打印机

    481. if (OpenPrinter(PrinterName, out hPrinter, ref defaults))

    482. {

    483. try

    484. {

    485. DeleteForm(hPrinter, PaperName);

    486. ClosePrinter(hPrinter);

    487. }

    488. catch

    489. {

    490.  
    491. }

    492. }

    493. }

    494. #endregion 删除已经存在的自定义纸张

    495. #region 指定的打印机设置以mm为单位的自定义纸张(Form)

    496. /**/

    497. /// <summary>

    498. /// 指定的打印机设置以mm为单位的自定义纸张(Form)

    499. /// </summary>

    500. /// <param name="PrinterName">打印机名称</param>

    501. /// <param name="PaperName">Form名称</param>

    502. /// <param name="WidthInMm">以mm为单位的宽度</param>

    503. /// <param name="HeightInMm">以mm为单位的高度</param>

    504. public static void AddCustomPaperSize(string PrinterName, string PaperName, float WidthInMm, float HeightInMm)

    505. {

    506. if (PlatformID.Win32NT == Environment.OSVersion.Platform)

    507. {

    508. const int PRINTER_ACCESS_USE = 0x00000008;

    509. const int PRINTER_ACCESS_ADMINISTER = 0x00000004;

    510. structPrinterDefaults defaults = new structPrinterDefaults();

    511. defaults.pDatatype = null;

    512. defaults.pDevMode = IntPtr.Zero;

    513. defaults.DesiredAccess = PRINTER_ACCESS_ADMINISTER | PRINTER_ACCESS_USE;

    514. IntPtr hPrinter = IntPtr.Zero;

    515. //打开打印机

    516. if (OpenPrinter(PrinterName, out hPrinter, ref defaults))

    517. {

    518. try

    519. {

    520. //如果Form存在删除之

    521. DeleteForm(hPrinter, PaperName);

    522. //创建并初始化FORM_INFO_1

    523. FormInfo1 formInfo = new FormInfo1();

    524. formInfo.Flags = 0;

    525. formInfo.pName = PaperName;

    526. formInfo.Size.width = (int)(WidthInMm * 1000.0);

    527. formInfo.Size.height = (int)(HeightInMm * 1000.0);

    528. formInfo.ImageableArea.left = 0;

    529. formInfo.ImageableArea.right = formInfo.Size.width;

    530. formInfo.ImageableArea.top = 0;

    531. formInfo.ImageableArea.bottom = formInfo.Size.height;

    532. if (!AddForm(hPrinter, 1, ref formInfo))

    533. {

    534. StringBuilder strBuilder = new StringBuilder();

    535. strBuilder.AppendFormat("向打印机 {1} 添加自定义纸张 {0} 失败!错误代号:{2}",

    536. PaperName, PrinterName, GetLastError());

    537. throw new ApplicationException(strBuilder.ToString());

    538. }

    539.  
    540. //初始化

    541. const int DM_OUT_BUFFER = 2;

    542. const int DM_IN_BUFFER = 8;

    543. structDevMode devMode = new structDevMode();

    544. IntPtr hPrinterInfo, hDummy;

    545. PRINTER_INFO_9 printerInfo;

    546. printerInfo.pDevMode = IntPtr.Zero;

    547. int iPrinterInfoSize, iDummyInt;

    548.  
    549.  
    550. int iDevModeSize = DocumentProperties(IntPtr.Zero, hPrinter, PrinterName, IntPtr.Zero, IntPtr.Zero, 0);

    551.  
    552. if (iDevModeSize < 0)

    553. throw new ApplicationException("无法取得DEVMODE结构的大小!");

    554.  
    555. //分配缓冲

    556. IntPtr hDevMode = Marshal.AllocCoTaskMem(iDevModeSize + 100);

    557.  
    558. //获取DEV_MODE指针

    559. int iRet = DocumentProperties(IntPtr.Zero, hPrinter, PrinterName, hDevMode, IntPtr.Zero, DM_OUT_BUFFER);

    560.  
    561. if (iRet < 0)

    562. throw new ApplicationException("无法获得DEVMODE结构!");

    563.  
    564. //填充DEV_MODE

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

    566.  
    567.  
    568. devMode.dmFields = 0x10000;

    569.  
    570. //FORM名称

    571. devMode.dmFormName = PaperName;

    572.  
    573. Marshal.StructureToPtr(devMode, hDevMode, true);

    574.  
    575. iRet = DocumentProperties(IntPtr.Zero, hPrinter, PrinterName,

    576. printerInfo.pDevMode, printerInfo.pDevMode, DM_IN_BUFFER | DM_OUT_BUFFER);

    577.  
    578. if (iRet < 0)

    579. throw new ApplicationException("无法为打印机设定打印方向!");

    580.  
    581. GetPrinter(hPrinter, 9, IntPtr.Zero, 0, out iPrinterInfoSize);

    582. if (iPrinterInfoSize == 0)

    583. throw new ApplicationException("调用GetPrinter方法失败!");

    584.  
    585. hPrinterInfo = Marshal.AllocCoTaskMem(iPrinterInfoSize + 100);

    586.  
    587. bool bSuccess = GetPrinter(hPrinter, 9, hPrinterInfo, iPrinterInfoSize, out iDummyInt);

    588.  
    589. if (!bSuccess)

    590. throw new ApplicationException("调用GetPrinter方法失败!");

    591.  
    592. printerInfo = (PRINTER_INFO_9)Marshal.PtrToStructure(hPrinterInfo, printerInfo.GetType());

    593. printerInfo.pDevMode = hDevMode;

    594.  
    595. Marshal.StructureToPtr(printerInfo, hPrinterInfo, true);

    596.  
    597. bSuccess = SetPrinter(hPrinter, 9, hPrinterInfo, 0);

    598.  
    599. if (!bSuccess)

    600. throw new Win32Exception(Marshal.GetLastWin32Error(), "调用SetPrinter方法失败,无法进行打印机设置!");

    601.  
    602. SendMessageTimeout(

    603. new IntPtr(HWND_BROADCAST),

    604. WM_SETTINGCHANGE,

    605. IntPtr.Zero,

    606. IntPtr.Zero,

    607. PrinterHelper.SendMessageTimeoutFlags.SMTO_NORMAL,

    608. 1000,

    609. out hDummy);

    610. }

    611. finally

    612. {

    613. ClosePrinter(hPrinter);

    614. }

    615. }

    616. else

    617. {

    618. StringBuilder strBuilder = new StringBuilder();

    619. strBuilder.AppendFormat("无法打开打印机{0}, 错误代号: {1}",

    620. PrinterName, GetLastError());

    621. throw new ApplicationException(strBuilder.ToString());

    622. }

    623. }

    624. else

    625. {

    626. structDevMode pDevMode = new structDevMode();

    627. IntPtr hDC = CreateDC(null, PrinterName, null, ref pDevMode);

    628. if (hDC != IntPtr.Zero)

    629. {

    630. const long DM_PAPERSIZE = 0x00000002L;

    631. const long DM_PAPERLENGTH = 0x00000004L;

    632. const long DM_PAPERWIDTH = 0x00000008L;

    633. pDevMode.dmFields = (int)(DM_PAPERSIZE | DM_PAPERWIDTH | DM_PAPERLENGTH);

    634. pDevMode.dmPaperSize = 256;

    635. pDevMode.dmPaperWidth = (short)(WidthInMm * 1000.0);

    636. pDevMode.dmPaperLength = (short)(HeightInMm * 1000.0);

    637. ResetDC(hDC, ref pDevMode);

    638. DeleteDC(hDC);

    639. }

    640. }

    641. }

    642. #endregion 指定的打印机设置以mm为单位的自定义纸张(Form)

    643. #region 获取本地打印机列表

    644. /**/

    645. /// <summary>

    646. /// 获取本地打印机列表

    647. /// 可以通过制定参数获取网络打印机

    648. /// </summary>

    649. /// <returns>打印机列表</returns>

    650. public static System.Collections.ArrayList GetPrinterList()

    651. {

    652. System.Collections.ArrayList alRet = new System.Collections.ArrayList();

    653. PRINTER_INFO_2[] Info2 = EnumPrintersByFlag(PrinterEnumFlags.PRINTER_ENUM_LOCAL);

    654. for (int i = 0; i < Info2.Length; i++)

    655. {

    656. alRet.Add(Info2[i].pPrinterName);

    657. }

    658. return alRet;

    659. }

    660. #endregion 获取本地打印机列表

    661.  
    662. #region 获取本机的默认打印机名称

    663. /**/

    664. /// <summary>

    665. /// 获取本机的默认打印机名称

    666. /// </summary>

    667. /// <returns>默认打印机名称</returns>

    668. public static string GetDeaultPrinterName()

    669. {

    670. StringBuilder dp = new StringBuilder(256);

    671. int size = dp.Capacity;

    672. if (GetDefaultPrinter(dp, ref size))

    673. {

    674. return dp.ToString();

    675. }

    676. else

    677. {

    678. return string.Empty;

    679. }

    680. }

    681. #endregion 获取本机的默认打印机名称

    682. #region 设置默认打印机

    683. /**/

    684. /// <summary>

    685. /// 设置默认打印机

    686. /// </summary>

    687. /// <param name="PrinterName">可用的打印机名称</param>

    688. public static void SetPrinterToDefault(string PrinterName)

    689. {

    690. SetDefaultPrinter(PrinterName);

    691. }

    692. #endregion 设置默认打印机

    693. #region 判断打印机是否在系统可用的打印机列表中

    694. /**/

    695. ///// <summary>

    696. ///// 判断打印机是否在系统可用的打印机列表中

    697. ///// </summary>

    698. ///// <param name="PrinterName">打印机名称</param>

    699. ///// <returns>是:在;否:不在</returns>

    700. public static bool PrinterInList(string PrinterName)

    701. {

    702. bool bolRet = false;

    703.  
    704. System.Collections.ArrayList alPrinters = GetPrinterList();

    705.  
    706. for (int i = 0; i < alPrinters.Count; i++)

    707. {

    708. if (PrinterName == alPrinters[i].ToString())

    709. {

    710. bolRet = true;

    711. break;

    712. }

    713. }

    714.  
    715. alPrinters.Clear();

    716. alPrinters = null;

    717.  
    718. return bolRet;

    719. }

    720. #endregion 判断打印机是否在系统可用的打印机列表中

    721. #region 判断表单是否在指定的打印机所支持的纸张列表中

    722. /**/

    723. ///// <summary>

    724. ///// 判断表单是否在指定的打印机所支持的纸张列表中,表单就是我们平常所说的纸张

    725. ///// </summary>

    726. ///// <param name="PrinterName">打印机名称</param>

    727. ///// <param name="PaperName">纸张名称</param>

    728. ///// <returns>是:在;否:不在</returns>

    729. public static bool FormInPrinter(string PrinterName, string PaperName)

    730. {

    731. bool bolRet = false;

    732.  
    733. System.Drawing.Printing.PrintDocument pd = new System.Drawing.Printing.PrintDocument();

    734.  
    735. pd.PrinterSettings.PrinterName = PrinterName;

    736.  
    737. foreach (System.Drawing.Printing.PaperSize ps in pd.PrinterSettings.PaperSizes)

    738. {

    739. if (ps.PaperName == PaperName)

    740. {

    741. bolRet = true;

    742. break;

    743. }

    744. }

    745.  
    746. pd.Dispose();

    747.  
    748. return bolRet;

    749. }

    750. #endregion 判断表单是否在指定的打印机所支持的纸张列表中

    751. #region 判断指定纸张的宽度和高度和与打印内容指定的宽度和高度是否匹配

    752. /**/

    753. /// <summary>

    754. /// 判断指定纸张的宽度和高度和与打印内容指定的宽度和高度是否匹配

    755. /// </summary>

    756. /// <param name="PrinterName">打印机名称</param>

    757. /// <param name="FormName">表单名称</param>

    758. /// <param name="Width">宽度</param>

    759. /// <param name="Height">高度</param>

    760. /// <returns></returns>

    761. public static bool FormSameSize(string PrinterName, string FormName, decimal Width, decimal Height)

    762. {

    763. bool bolRet = false;

    764.  
    765. System.Drawing.Printing.PrintDocument pd = new System.Drawing.Printing.PrintDocument();

    766.  
    767. pd.PrinterSettings.PrinterName = PrinterName;

    768.  
    769. foreach (System.Drawing.Printing.PaperSize ps in pd.PrinterSettings.PaperSizes)

    770. {

    771. if (ps.PaperName == FormName)

    772. {

    773. decimal decWidth = FromInchToCM(System.Convert.ToDecimal(ps.Width));

    774. decimal decHeight = FromInchToCM(System.Convert.ToDecimal(ps.Height));

    775. //只要整数位相同即认为是同一纸张,毕竟inch到cm的转换并不能整除

    776. if (Math.Round(decWidth, 0) == Math.Round(Width, 0) && Math.Round(decHeight, 0) == Math.Round(Height, 0))

    777. bolRet = true;

    778. break;

    779. }

    780. }

    781.  
    782. pd.Dispose();

    783.  
    784. return bolRet;

    785. }

    786. #endregion 判断指定纸张的宽度和高度和与打印内容指定的宽度和高度是否匹配

    787. #region 英寸到厘米的转换

    788. /**/

    789. /// <summary>

    790. /// 英寸到厘米的转换

    791. /// /* = = = = = = = = = = = = = = = = *\

    792. /// | 换算一下计量单位,将其换算成厘米 |

    793. /// | 厘米 像素 英寸 |

    794. /// | 1 38 0.395 |

    795. /// | 0.026 1 0.01 |

    796. /// | 2.54 96 1 |

    797. /// \* = = = = = = = = = = = = = = = = */

    798. /// </summary>

    799. /// <param name="inch">英寸数</param>

    800. /// <returns>厘米数,两位小数</returns>

    801. ///

    802. public static decimal FromInchToCM(decimal inch)

    803. {

    804. return Math.Round((System.Convert.ToDecimal((inch / 100)) * System.Convert.ToDecimal(2.5400)), 2);

    805. }

    806. #endregion 英寸到厘米的转换

    807.  
    808.  
    809.  
    810. [DllImport("winspool.Drv", EntryPoint = "OpenPrinterA", SetLastError = true, CharSet = CharSet.Ansi, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]

    811. public static extern bool OpenPrinter([MarshalAs(UnmanagedType.LPStr)] string szPrinter, out IntPtr hPrinter, IntPtr pd);

    812.  
    813.  
    814. //[DllImport("winspool.Drv", EntryPoint = "ClosePrinter", SetLastError = true, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]

    815. //public static extern bool ClosePrinter(IntPtr hPrinter);

    816.  
    817.  
    818. [DllImport("winspool.Drv", EntryPoint = "StartDocPrinterA", SetLastError = true, CharSet = CharSet.Ansi, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]

    819. public static extern bool StartDocPrinter(IntPtr hPrinter, Int32 level, [In, MarshalAs(UnmanagedType.LPStruct)] DOCINFOA di);

    820.  
    821.  
    822. [DllImport("winspool.Drv", EntryPoint = "EndDocPrinter", SetLastError = true, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]

    823. public static extern bool EndDocPrinter(IntPtr hPrinter);

    824.  
    825.  
    826. [DllImport("winspool.Drv", EntryPoint = "StartPagePrinter", SetLastError = true, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]

    827. public static extern bool StartPagePrinter(IntPtr hPrinter);

    828.  
    829.  
    830. [DllImport("winspool.Drv", EntryPoint = "EndPagePrinter", SetLastError = true, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]

    831. public static extern bool EndPagePrinter(IntPtr hPrinter);

    832.  
    833.  
    834. [DllImport("winspool.Drv", EntryPoint = "WritePrinter", SetLastError = true, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]

    835. public static extern bool WritePrinter(IntPtr hPrinter, IntPtr pBytes, Int32 dwCount, out Int32 dwWritten);

    836.  
    837. /// <summary>

    838. /// 该方法把非托管内存中的字节数组发送到打印机的打印队列

    839. /// </summary>

    840. /// <param name="szPrinterName">打印机名称</param>

    841. /// <param name="pBytes">非托管内存指针</param>

    842. /// <param name="dwCount">字节数</param>

    843. /// <returns>成功返回true,失败时为false</returns>

    844. public static bool SendBytesToPrinter(string szPrinterName, IntPtr pBytes, Int32 dwCount)

    845. {

    846. Int32 dwError = 0, dwWritten = 0;

    847. IntPtr hPrinter = new IntPtr(0);

    848. DOCINFOA di = new DOCINFOA();

    849. bool bSuccess = false;

    850.  
    851. di.pDocName = "My C#.NET RAW Document";

    852. di.pDataType = "RAW";

    853.  
    854. try

    855. {

    856. // 打开打印机

    857. if (OpenPrinter(szPrinterName.Normalize(), out hPrinter, IntPtr.Zero))

    858. {

    859. // 启动文档打印

    860. if (StartDocPrinter(hPrinter, 1, di))

    861. {

    862. // 开始打印

    863. if (StartPagePrinter(hPrinter))

    864. {

    865. // 向打印机输出字节

    866. bSuccess = WritePrinter(hPrinter, pBytes, dwCount, out dwWritten);

    867. EndPagePrinter(hPrinter);

    868. }

    869. EndDocPrinter(hPrinter);

    870. }

    871. ClosePrinter(hPrinter);

    872. }

    873. if (bSuccess == false)

    874. {

    875. dwError = Marshal.GetLastWin32Error();

    876. }

    877. }

    878. catch (Win32Exception ex)

    879. {

    880. WriteLog(ex.Message);

    881. bSuccess = false;

    882. }

    883. return bSuccess;

    884. }

    885.  
    886.  
    887. /// <summary>

    888. /// 发送文件到打印机方法

    889. /// </summary>

    890. /// <param name="szPrinterName">打印机名称</param>

    891. /// <param name="szFileName">打印文件的路径</param>

    892. /// <returns></returns>

    893. public static bool SendFileToPrinter(string szPrinterName, string szFileName)

    894. {

    895. bool bSuccess = false;

    896. try

    897. {

    898. // 打开文件

    899. FileStream fs = new FileStream(szFileName, FileMode.Open);

    900.  
    901. // 将文件内容读作二进制

    902. BinaryReader br = new BinaryReader(fs);

    903.  
    904. // 定义字节数组

    905. Byte[] bytes = new Byte[fs.Length];

    906.  
    907. // 非托管指针

    908. IntPtr pUnmanagedBytes = new IntPtr(0);

    909.  
    910. int nLength;

    911.  
    912. nLength = Convert.ToInt32(fs.Length);

    913.  
    914. // 读取文件内容到字节数组

    915. bytes = br.ReadBytes(nLength);

    916.  
    917. // 为这些字节分配一些非托管内存

    918. pUnmanagedBytes = Marshal.AllocCoTaskMem(nLength);

    919.  
    920. // 将托管字节数组复制到非托管内存指针

    921. Marshal.Copy(bytes, 0, pUnmanagedBytes, nLength);

    922.  
    923. // 将非托管字节发送到打印机

    924. bSuccess = SendBytesToPrinter(szPrinterName, pUnmanagedBytes, nLength);

    925.  
    926. // 释放先前分配的非托管内存

    927. Marshal.FreeCoTaskMem(pUnmanagedBytes);

    928.  
    929. fs.Close();

    930. fs.Dispose();

    931. }

    932. catch (Win32Exception ex)

    933. {

    934. WriteLog(ex.Message);

    935. bSuccess = false;

    936. }

    937. return bSuccess;

    938. }

    939.  
    940. /// <summary>

    941. /// 将字符串发送到打印机方法

    942. /// </summary>

    943. /// <param name="szPrinterName">打印机名称</param>

    944. /// <param name="szString">打印的字符串</param>

    945. /// <returns></returns>

    946. public static bool SendStringToPrinter(string szPrinterName, string szString)

    947. {

    948. bool flag = false;

    949. try

    950. {

    951. IntPtr pBytes;

    952. Int32 dwCount;

    953.  
    954. // 获取字符串长度

    955. dwCount = szString.Length;

    956.  
    957. // 将字符串复制到非托管 COM 任务分配的内存非托管内存块,并转换为 ANSI 文本

    958. pBytes = Marshal.StringToCoTaskMemAnsi(szString);

    959.  
    960. // 将已转换的 ANSI 字符串发送到打印机

    961. flag = SendBytesToPrinter(szPrinterName, pBytes, dwCount);

    962.  
    963. // 释放先前分配的非托管内存

    964. Marshal.FreeCoTaskMem(pBytes);

    965. }

    966. catch (Win32Exception ex)

    967. {

    968. WriteLog(ex.Message);

    969. flag = false;

    970. }

    971. return flag;

    972. }

    973.  
    974. /// <summary>

    975. /// 写入日志方法

    976. /// </summary>

    977. /// <param name="msg">记录信息</param>

    978. public static void WriteLog(string msg)

    979. {

    980. string str = string.Empty;

    981. string path = AppDomain.CurrentDomain.BaseDirectory + "log\\" + DateTime.Now.ToString("yyyy-MM-dd") + ".txt";

    982.  
    983. FileStream filestream = new FileStream(path, FileMode.OpenOrCreate);

    984.  
    985. str += "************" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "************\r\n";

    986. str += msg;

    987. str += "************" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "************\r\n";

    988.  
    989. FileStream fs = new FileStream(path, FileMode.Append);

    990. StreamWriter sw = new StreamWriter(fs, System.Text.Encoding.Default);

    991. sw.WriteLine(str);

    992.  
    993. sw.Flush();

    994.  
    995. sw.Close();

    996. sw.Dispose();

    997.  
    998. fs.Close();

    999. fs.Dispose();

    1000. }

    1001. }

    1002.  
    1003. [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]

    1004. public class DOCINFOA

    1005. {

    1006. [MarshalAs(UnmanagedType.LPStr)]

    1007. public string pDocName;

    1008. [MarshalAs(UnmanagedType.LPStr)]

    1009. public string pOutputFile;

    1010. [MarshalAs(UnmanagedType.LPStr)]

    1011. public string pDataType;

    1012. }

    1013. }


            我们可以看到,这些函数都是调用的winspool.drv 这个windows的驱动来实现API调用的,这里我们还真应该好好琢磨琢磨。

  • 相关阅读:
    05 库的简单操作
    04 基本的MySQL语句
    03 MySQL安装和基本管理
    02 数据库概述
    01 MySQL入门了解
    Django-组件拾遗
    bootstrap基础讲解
    jQuery练习
    前端基础之Jquery
    15 Django组件-中间件
  • 原文地址:https://www.cnblogs.com/grj001/p/12223558.html
Copyright © 2011-2022 走看看