我正在构建winforms .net应用程序,我在网络上有一个E-Pos打印机, 使用以下代码: 在表格加载打印机初始化:
explorer = new PosExplorer(this);
DeviceInfo receiptPrinterDevice = explorer.GetDevice("PosPrinter", Properties.Settings.Default.KitchenPrinter); //May need to change this if you don't use a logicial name or use a different one.
kitchenPrinter = (PosPrinter)explorer.CreateInstance(receiptPrinterDevice);
ConnectToPrinter();
private void ConnectToPrinter()
{
kitchenPrinter.Open();
kitchenPrinter.Claim(10000);
kitchenPrinter.DeviceEnabled = true;
}
打印按钮上的函数调用:
private void PrintReceipt()
{
try
{ kitchenPrinter.PrintNormal(PrinterStation.Receipt, "test");
}
finally
{
}
}
当我想切换到其他表格时,我称之为断开连接功能
DisconnectFromPrinter(kitchenPrinter);
Reporting frm = new Reporting(curuser);
frm.Show();
this.Hide();
private void DisconnectFromPrinter(PosPrinter kitchenPrinter)
{
try
{
kitchenPrinter.Release();
kitchenPrinter.Close();
}
catch { }
}
它打印成功一次,当下次打印时按下打印和异常
方法ClaimDevice引发了异常。尝试对设备执行非法或不受支持的操作,或者使用了无效的参数值。
任何建议?
答案 0 :(得分:0)
由于Release命令无效,并且每次我加载表单时Claim命令都会抛出错误,因为它之前已被声明。
所以我创建了一个单独的Class Called" createPOS"
class createPOS
{
public static PosExplorer explorer;
public static PosPrinter kitchenPrinter;
public static void createPos()
{
explorer = new PosExplorer();
DeviceInfo receiptPrinterDevice = explorer.GetDevice("PosPrinter", Properties.Settings.Default.KitchenPrinter); //May need to change this if you don't use a logicial name or use a different one.
kitchenPrinter = (PosPrinter)explorer.CreateInstance(receiptPrinterDevice);
kitchenPrinter.Open();
kitchenPrinter.Claim(10000);
kitchenPrinter.DeviceEnabled = true;
}
public static void Print(string text){
if (kitchenPrinter.Claimed)
PrintTextLine(kitchenPrinter, text); // kitchenPrinter.PrintNormal(PrinterStation.Receipt, text ); //Print text, then a new line character.
}
private static void PrintTextLine(PosPrinter printer, string text)
{
if (text.Length < printer.RecLineChars)
printer.PrintNormal(PrinterStation.Receipt, text + Environment.NewLine); //Print text, then a new line character.
else if (text.Length > printer.RecLineChars)
printer.PrintNormal(PrinterStation.Receipt, TruncateAt(text, printer.RecLineChars)); //Print exactly as many characters as the printer allows, truncating the rest, no new line character (printer will probably auto-feed for us)
else if (text.Length == printer.RecLineChars)
printer.PrintNormal(PrinterStation.Receipt, text + Environment.NewLine); //Print text, no new line character, printer will probably auto-feed for us.
}
private static string TruncateAt(string text, int maxWidth)
{
string retVal = text;
if (text.Length > maxWidth)
retVal = text.Substring(0, maxWidth);
return retVal;
}
}
并在登录表单上,只有在我初始化打印机后才能访问它
createPOS.createPos();
在MainForm上我调用了打印方法:
createPOS.Print("This allows me to Print Several times");
通过这种方式,我可以多次打印,甚至可以导航到其他形式,然后再回来工作正常。
谢谢你们。