我正在构建winforms .net应用程序,我在网络上有一个below打印机,使用下面的代码:在表单加载打印机初始化:
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抛出一个异常。试图对设备执行非法或不受支持的操作,或者使用无效的参数值。。
有什么建议吗?
发布于 2017-03-03 17:30:03
因为Release命令并不有效,而且可能声明命令每次加载表单时都会抛出一个错误,因为它是在前面声明的。
因此,我创建了一个名为"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");这样的话,我可以打印几次,甚至导航到其他表单,然后再回来,效果很好。
谢谢你们。
https://stackoverflow.com/questions/42573417
复制相似问题