#region 串口打印
//打印函数,参数为打印机的命令或者其他文本!
public bool COMWrite(string portName, int baudRate, Parity parity, int dataBits, StopBits stopBits, string myString)
{
try
{
SerialPort ComPort = new SerialPort(portName, baudRate, parity, dataBits, stopBits);
if (ComPort.IsOpen)
{
ComPort.Close();
}
ComPort.Open();
ComPort.WriteLine(myString);
ComPort.Close();
return true;
}
catch (Exception ex)
{
return false;
}
}
#endregion 并口打印
#region 并口打印
[StructLayout(LayoutKind.Sequential)]
private struct OVERLAPPED
{
int Internal;
int InternalHigh;
int Offset;
int OffSetHigh;
int hEvent;
}
[DllImport("kernel32.dll")]
private static extern int CreateFile(string lpFileName, uint dwDesiredAccess, int dwShareMode, int lpSecurityAttributes, int dwCreationDisposition, int dwFlagsAndAttributes, int hTemplateFile);
[DllImport("kernel32.dll")]
private static extern bool WriteFile(int hFile, byte[] lpBuffer, int nNumberOfBytesToWriter, out int lpNumberOfBytesWriten, out OVERLAPPED lpOverLapped);
[DllImport("kernel32.dll")]
private static extern bool CloseHandle(int hObject);
private int iHandle;
//打开LPT 端口
public bool LPTOpen()
{
iHandle = CreateFile("lpt1", 0x40000000, 0, 0, 3, 0, 0);
if (iHandle != -1)
{
return true;
}
else
{
return false;
}
}
//打印函数,参数为打印机的命令或者其他文本!
public bool LPTWrite(string myString)
{
if (!LPTOpen()) { return false; }
if (iHandle != 1)
{
int i;
OVERLAPPED x;
byte[] mybyte = System.Text.Encoding.Default.GetBytes(myString);
//return WriteFile(iHandle, mybyte, mybyte.Length, out i, out x);
if (WriteFile(iHandle, mybyte, mybyte.Length, out i, out x))
{
LPTClose();
return true;
}
else
{
return false;
}
}
else
{
throw new Exception("端口未打开~!");
return false;
}
}
//关闭打印端口
public bool LPTClose()
{
return CloseHandle(iHandle);
}
#endregion 并口打印