博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
C# 控制打印机切纸[转载]
阅读量:6344 次
发布时间:2019-06-22

本文共 7065 字,大约阅读时间需要 23 分钟。

调用代码:

//不同的打印机需要不同的参数,这个参数应该可以在打印机的编程文档中找到string str = ((char)29).ToString() + ((char)86).ToString() + ((char)0).ToString();byte[] p_Byte = System.Text.Encoding.Default.GetBytes(str);string p_PrintName = "打印机名称";
WinApiPrintByte(p_PrintName, p_Byte);
复制代码

 

方法:

/// /// 发送数据到打印机 /// ///打印机名称 ///切纸数据 public static void WinApiPrintByte(string p_PrintName, byte[] p_Byte) {
if (p_PrintName != null && p_PrintName.Length > 0) {
IntPtr _PrintHandle; IntPtr _JobHandle = Marshal.AllocHGlobal(100); if (OpenPrinter(p_PrintName, out _PrintHandle, IntPtr.Zero)) {
ADDJOB_INFO_1 _JobInfo = new ADDJOB_INFO_1(); int _Size; AddJob(_PrintHandle, 1, _JobHandle, 100, out _Size); _JobInfo = (ADDJOB_INFO_1)Marshal.PtrToStructure(_JobHandle, typeof(ADDJOB_INFO_1)); //System.IO.File.WriteAllBytes(p_PrintName, p_Byte); System.IO.File.WriteAllBytes(_JobInfo.lpPath, p_Byte); ScheduleJob(_PrintHandle, _JobInfo.JobID); ClosePrinter(_PrintHandle); Marshal.FreeHGlobal(_JobHandle); } } } [DllImport("winspool.drv", CharSet = CharSet.Auto)] public static extern bool OpenPrinter([MarshalAs(UnmanagedType.LPTStr)]string strPrinterName, out IntPtr ptrPrinter, IntPtr ptrDefalut); [DllImport("winspool.drv", CharSet = CharSet.Auto)] public static extern bool ClosePrinter(IntPtr ptrPrinter); [DllImport("winspool.drv", CharSet = CharSet.Auto)] public static extern bool AddJob(IntPtr ptrPrinter, Int32 iLevel, IntPtr ptrJob, Int32 iSize, out Int32 iCpSize); [DllImport("winspool.drv", CharSet = CharSet.Auto)] public static extern bool ScheduleJob(IntPtr ptrPrinter, Int32 JobID); [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)] public struct ADDJOB_INFO_1 {
[MarshalAs(UnmanagedType.LPTStr)] public string lpPath; public Int32 JobID; }
复制代码

 

说明:本段代码来源于网络。

        在热敏小票打印机打印机上测试可用

        看原文介绍,应该也可用于其他带有切纸刀的打印机

另外附带微软提供的打印类:

using System; using System.Drawing; using System.Drawing.Printing; using System.IO; using System.Runtime.InteropServices; using System.Windows.Forms; publicclassRawPrinterHelper {
  // Structure and API declarions:   [StructLayout(LayoutKind.Sequential,CharSet=CharSet.Ansi)]   publicclass DOCINFOA   {
    [MarshalAs(UnmanagedType.LPStr)]publicstring pDocName;     [MarshalAs(UnmanagedType.LPStr)]publicstring pOutputFile;     [MarshalAs(UnmanagedType.LPStr)]publicstring pDataType;   }   [DllImport("winspool.Drv",EntryPoint="OpenPrinterA",SetLastError=true,CharSet=CharSet.Ansi,ExactSpelling=true,CallingConvention=CallingConvention.StdCall)]   publicstaticextern bool OpenPrinter([MarshalAs(UnmanagedType.LPStr)]string szPrinter,outIntPtr hPrinter,IntPtr pd);   [DllImport("winspool.Drv",EntryPoint="ClosePrinter",SetLastError=true,ExactSpelling=true,CallingConvention=CallingConvention.StdCall)]   publicstaticextern bool ClosePrinter(IntPtr hPrinter);   [DllImport("winspool.Drv",EntryPoint="StartDocPrinterA",SetLastError=true,CharSet=CharSet.Ansi,ExactSpelling=true,CallingConvention=CallingConvention.StdCall)]   publicstaticextern bool StartDocPrinter(IntPtr hPrinter,Int32 level,  [In,MarshalAs(UnmanagedType.LPStruct)] DOCINFOA di);   [DllImport("winspool.Drv",EntryPoint="EndDocPrinter",SetLastError=true,ExactSpelling=true,CallingConvention=CallingConvention.StdCall)]   publicstaticextern bool EndDocPrinter(IntPtr hPrinter);   [DllImport("winspool.Drv",EntryPoint="StartPagePrinter",SetLastError=true,ExactSpelling=true,CallingConvention=CallingConvention.StdCall)]   publicstaticextern bool StartPagePrinter(IntPtr hPrinter);   [DllImport("winspool.Drv",EntryPoint="EndPagePrinter",SetLastError=true,ExactSpelling=true,CallingConvention=CallingConvention.StdCall)]   publicstaticextern bool EndPagePrinter(IntPtr hPrinter);   [DllImport("winspool.Drv",EntryPoint="WritePrinter",SetLastError=true,ExactSpelling=true,CallingConvention=CallingConvention.StdCall)]   publicstaticextern bool WritePrinter(IntPtr hPrinter,IntPtr pBytes,Int32 dwCount,outInt32 dwWritten );   // SendBytesToPrinter()   // When the function is given a printer name and an unmanaged array   // of bytes, the function sends those bytes to the print queue.   // Returns true on success, false on failure.   publicstatic bool SendBytesToPrinter(string szPrinterName,IntPtr pBytes,Int32 dwCount)   {
    Int32    dwError =0, dwWritten =0;     IntPtr    hPrinter =newIntPtr(0);     DOCINFOA    di =new DOCINFOA();     bool    bSuccess =false;// Assume failure unless you specifically succeed.     di.pDocName ="My C#.NET RAW Document";     di.pDataType ="RAW";     // Open the printer.     if(OpenPrinter( szPrinterName.Normalize(),out hPrinter,IntPtr.Zero))     {
      // Start a document.       if(StartDocPrinter(hPrinter,1, di))       {
        // Start a page.         if(StartPagePrinter(hPrinter))         {
          // Write your bytes.           bSuccess =WritePrinter(hPrinter, pBytes, dwCount,out dwWritten);           EndPagePrinter(hPrinter);         }         EndDocPrinter(hPrinter);       }       ClosePrinter(hPrinter);     }     // If you did not succeed, GetLastError may give more information     // about why not.     if( bSuccess ==false)     {
      dwError =Marshal.GetLastWin32Error();     }     return bSuccess;   }   publicstatic bool SendFileToPrinter(string szPrinterName,string szFileName )   {
    // Open the file.     FileStream fs =newFileStream(szFileName,FileMode.Open);     // Create a BinaryReader on the file.     BinaryReader br =newBinaryReader(fs);     // Dim an array of bytes big enough to hold the file's contents.     Byte[]bytes =newByte[fs.Length];     bool bSuccess =false;     // Your unmanaged pointer.     IntPtr pUnmanagedBytes =newIntPtr(0);     int nLength;     nLength =Convert.ToInt32(fs.Length);     // Read the contents of the file into the array.     bytes = br.ReadBytes( nLength );     // Allocate some unmanaged memory for those bytes.     pUnmanagedBytes =Marshal.AllocCoTaskMem(nLength);     // Copy the managed byte array into the unmanaged array.     Marshal.Copy(bytes,0, pUnmanagedBytes, nLength);     // Send the unmanaged bytes to the printer.     bSuccess =SendBytesToPrinter(szPrinterName, pUnmanagedBytes, nLength);     // Free the unmanaged memory that you allocated earlier.     Marshal.FreeCoTaskMem(pUnmanagedBytes);     return bSuccess;   }   publicstatic bool SendStringToPrinter(string szPrinterName,string szString )   {
    IntPtr pBytes;     Int32 dwCount;     // How many characters are in the string?     // Fix from Nicholas Piasecki:     // dwCount = szString.Length;     dwCount =(szString.Length+1)*Marshal.SystemMaxDBCSCharSize;     // Assume that the printer is expecting ANSI text, and then convert     // the string to ANSI text.     pBytes =Marshal.StringToCoTaskMemAnsi(szString);     // Send the converted ANSI string to the printer.     SendBytesToPrinter(szPrinterName, pBytes, dwCount);     Marshal.FreeCoTaskMem(pBytes);     returntrue;   } }

转载于:https://www.cnblogs.com/dannyqiu/articles/2321919.html

你可能感兴趣的文章
Spring Boot 自动配置之@EnableAutoConfiguration
查看>>
为了学习go我从0开始用beego写了一个简单个人博客(2)登陆管理
查看>>
职业女性:学会减压救自己!
查看>>
OSChina 周一乱弹 —— 这个需求很简单!
查看>>
OSChina 周一乱弹 —— 我当你是朋友,你却……
查看>>
[Android官方API阅读]___<Device Compatibility>
查看>>
如何写出好的产品需求文档(PRD)?
查看>>
Flex Chart
查看>>
Python中实用却不常见的小技巧
查看>>
012# Adempiere系统的贸易流程(一)
查看>>
(一)阅读器客户端开发实战_引言
查看>>
为何禁用MyBatis缓存
查看>>
手机安装 apk 出现“解析包时出现问题”
查看>>
Oracle用户被锁定解决方法
查看>>
485总线的概念
查看>>
我的友情链接
查看>>
web前端笔记
查看>>
import 路径
查看>>
使用optimizely做A/B测试
查看>>
finally知识讲解
查看>>