第一点:
const uint GENERIC_READ =0x80000000;
const uint GENERIC_WRITE = 0x40000000;
const int OPEN_EXISTING = 3;
private FileStream fs=null;
IntPtr iHandle;
[DllImport("kernel32.dll")]
public static extern IntPtr CreateFileA(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 nNumberOfBytesToWrite,
ref int lpNumberOfBytesWritten,
ref int i
);
[DllImport("kernel32.dll")]
private static extern bool CloseHandle(IntPtr hObject);
第二点:
protected void imageButton1_Click(object sender, ImageClickEventArgs e)
{
ShopCart mycart = CartCtroller.GetCart();
iHandle = CreateFileA("LPT1", GENERIC_READ | GENERIC_WRITE, 0, 0, OPEN_EXISTING, 0, 0);
if (iHandle.ToInt32() == -1)
{
Jscript.AjaxRunJs(this.Page, "alert('没有连接打印机或者打印机端口不是LPT1!')");
return;
}
else
{
fs = new FileStream(iHandle, FileAccess.ReadWrite);
//for (int i = 0; i < 5; i++)
//{
// fs.WriteByte(0x0A); //走纸(忘记了可能是这个)
//}
//StreamReader sr = new StreamReader(fs); //读数据;
//StreamWriter sw = new StreamWriter(fs, System.Text.Encoding.Default); //些数据;
if (mycart.Count == 0)
{
Jscript.AjaxRunJs(this.Page, "alert('请先购买产品!')");
return;
}
byte[] buf = new byte[500];
char ESC = (char)(27);
char GS = (char)(29);
char LF = (char)(10);
//读出数据
StringBuilder SEND = new StringBuilder();
//SEND.Append(LF.ToString());
char c1 = (char)60;
char c2 = (char)0;
SEND.Append(GS.ToString() + "L" + c1.ToString() + c2.ToString());
SEND.Append(ESC + "D" + Convert.ToChar(25) + Convert.ToChar(30) + Convert.ToChar(0));
string dt = DateTime.Now.ToString();
string mingcheng = "产品名称:";
string miaoshu = "产品描述:";
string shuliang = "购买数量:";
string zhi = "支";
SEND.Append(LF.ToString());
SEND.Append("欢 迎 光 临 - 上海金福");
SEND.Append("\r\n");
SEND.Append("-------------------------------");
SEND.Append(LF.ToString());
SEND.Append("购买时间:"+dt);
SEND.Append("\r\n");
SEND.Append("-------------------------------");
SEND.Append(LF.ToString());
SEND.Append(LF.ToString());
for (int i = 0; i < mycart.Count; i++)
{
modelArrayProduct temp = (modelArrayProduct)mycart[i];
SEND.Append(mingcheng + temp.T_name);
SEND.Append("\r\n");
SEND.Append(miaoshu + temp.T_miaoshu);
SEND.Append("\r\n");
SEND.Append(shuliang + temp.T_shuliang.ToString() + zhi);
SEND.Append("\r\n");
SEND.Append("-------------------------------");
SEND.Append(LF.ToString());
}
//走纸
SEND.Append(LF.ToString());
SEND.Append(LF.ToString());
SEND.Append(LF.ToString());
SEND.Append(LF.ToString());
SEND.Append(GS + "V" + Convert.ToChar(1));
//字符类型转换
Encoding utf8 = Encoding.GetEncoding(65001);
Encoding gb2312 = Encoding.GetEncoding("gb2312");//Encoding.Default ,936
byte[] tempa = utf8.GetBytes(SEND.ToString());
buf = Encoding.Convert(utf8, gb2312, tempa);
fs.Write(buf, 0, buf.Length);
fs.Close();
}
CloseHandle(iHandle);
}