// C # control the printer (directly send the printer command to the printer)
// A printer control class, which is very useful. It uses windows api to control the lpt port. The method for controlling the bar code printer is as follows: Write the printer command to a file and then use it.
// Code:
Using System;
Using System. Collections. Generic;
Using System. Text;
Using System. Runtime. InteropServices;
Namespace LPTControls
{
Public class LPTControls
{
[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 dw1_mode, 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;
// Open the LPT Port
Public bool Open ()
{
IHandle = CreateFile ("lpt1", 0x40000000, 0, 0, 3, 0, 0 );
If (iHandle! =-1)
{
Return true;
}
Else
{
Return false;
}
}
// Print function. The parameter is the printer command or other text!
Public bool Write (string MyString)
{
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 );
}
Else
{
Throw new Exception ("port not opened ~! ");
}
}
// Close the print Port
Public bool Close ()
{
Return CloseHandle (iHandle );
}
}
}
//************************************** *************************
// Usage
Private void button#click (object sender, EventArgs e)
{
LPTControls. LPTControls lpt = new LPTControls. LPTControls ();
String mycommanglines = System. IO. File. ReadAllText ("print.txt"); // the command of the bar code machine is written in print.txt.
Lpt. Open ();
Lpt. Write (mycommanglines );
Lpt. Close ();
}