C# 调用系统API函数直接连接pos打印机 打印

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
/// <summary>
/// PrintPos 的摘要说明
/// </summary>
public class PrintPos
{

        private FileStream fs = null;
        [DllImport("kernel32.dll")]//调用系统API打印函数
        public static extern IntPtr CreateFile
            (
            string FileName,          // file name
        uint DesiredAccess,       // access mode
        uint ShareMode,           // share mode
        uint SecurityAttributes,  // Security Attributes
        uint CreationDisposition, // how to create
        uint FlagsAndAttributes,  // file attributes
        int hTemplateFile         // handle to template file

            );

    public PrintPos()
    {
        //
        // TODO: 在此处添加构造函数逻辑
        //
    }
    /// <summary>
    /// 开始打印,本地打印机ltp1 端口打印 调用方法:PrintPos.PrintPage("dsdfdsfdsfsdfdsfsdfdsfs");
    /// </summary>
    /// <param name="strPos"></param>
    /// <returns></returns>
    public string PrintPage(string strPos)
    {
        IntPtr iHandle = CreateFile("LPT1", 0x40000000, 0, 0, 3, 0, 0);
        //判断是否连接上打印机 -1为false
        if (iHandle.ToInt32() == -1)
        {
            return "没有连接到打印机";
        }
        else
        {
            fs = new FileStream(iHandle, FileAccess.ReadWrite);
            //StreamReader sr = new StreamReader(fs);
            StreamWriter sw = new StreamWriter(fs, Encoding.Default);
            sw.WriteLine(strPos, 0, 500);
            sw.Close();
            fs.Close();
            return "已经成功连接打印机";
        }
    }
}

原文地址:https://www.cnblogs.com/zahxz/p/2794866.html