C# 使用C/S模式操作小票机打印

时间:2021-08-22 17:43:25

此方式适用于市场上大多数的小票机 佳博、POS58 等,不适用于有些标签打印机 比如斑马打印机等

直接贴代码:

 private FileStream fs = null;
[DllImport("kernel32.dll", CharSet = CharSet.Auto)]//调用系统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
string hTemplateFile // handle to template file
); /// <summary>
/// 打印小票
/// </summary>
/// <param name="msg"></param>
/// <returns></returns>
public string PrintMsg(string PosPort, string msg, bool isOpenMoneyBox)
{
try
{
IntPtr iHandle = CreateFile(PosPort, 0x40000000, , , , , null);
if (iHandle.ToInt32() == -)
{
return "票机连接失败.或者端口号错误.请测试打印机是否正常!";
}
else
{
try
{
fs = new FileStream(iHandle, FileAccess.ReadWrite);
StreamWriter sw = new StreamWriter(fs, System.Text.Encoding.Default); //写数据
sw.WriteLine(msg);
//开启钱箱
if (isOpenMoneyBox)
{
sw.Write(((char)).ToString() + "p" + ((char)).ToString() + ((char)).ToString() + ((char)).ToString());
}
sw.Flush();
sw.Close();
fs.Close();
return "";
}
catch (Exception ex)
{
return ex.InnerException == null ? ex.Message : ex.InnerException.Message;
}
}
}
catch (Exception exp)
{
return "TPL或者COM口连接失败!";
}
}