C# 操作并口类,并口通信

c#已提供了串口通信组件SerialPort,但是C#并没有提供直接的并口通信组件,只好通过调用API来与并口通信

 

代码
 
   
1 using System;
2   using System.Runtime.InteropServices;
3   namespace LptPrint_test
4 {
5 /// <summary>
6 /// LPTControl 的摘要说明。
7 /// </summary>
8   public class LPTControl
9 {
10 private string LptStr = " lpt1 " ;
11 public LPTControl( string l_LPT_Str)
12 {
13 //
14 // TODO: 在此处添加构造函数逻辑
15 //
16 LptStr = l_LPT_Str;
17 }
18 [StructLayout(LayoutKind.Sequential)]
19 private struct OVERLAPPED
20 {
21 int Internal;
22 int InternalHigh;
23 int Offset;
24 int OffSetHigh;
25 int hEvent;
26 }
27 [DllImport( " kernel32.dll " )]
28 private static extern int CreateFile( string lpFileName, uint dwDesiredAccess, int dwShareMode, int lpSecurityAttributes, int dwCreationDisposition, int dwFlagsAndAttributes, int hTemplateFile);
29 [DllImport( " kernel32.dll " )]
30 private static extern bool WriteFile( int hFile, byte [] lpBuffer, int nNumberOfBytesToWrite, ref int lpNumberOfBytesWritten, ref OVERLAPPED lpOverlapped);
31 [DllImport( " kernel32.dll " )]
32 private static extern bool CloseHandle( int hObject);
33 private int iHandle;
34 public bool Open()
35 {
36 iHandle = CreateFile(LptStr, 0x40000000 , 0 , 0 , 3 , 0 , 0 );
37 if (iHandle != - 1 )
38 {
39 return true ;
40 }
41 else
42 {
43 return false ;
44 }
45 }
46 public bool Write(String Mystring)
47 {
48 if (iHandle != - 1 )
49 {
50 OVERLAPPED x = new OVERLAPPED();
51 int i = 0 ;
52 byte [] mybyte = System.Text.Encoding.Default.GetBytes(Mystring);
53 bool b = WriteFile(iHandle, mybyte, mybyte.Length, ref i, ref x);
54 return b;
55 }
56 else
57 {
58 throw new Exception( " 不能连接到打印机! " );
59 }
60 }
61 public bool Write( byte [] mybyte)
62 {
63 if (iHandle != - 1 )
64 {
65 OVERLAPPED x = new OVERLAPPED();
66 int i = 0 ;
67 WriteFile(iHandle, mybyte, mybyte.Length, ref i, ref x);
68 return true ;
69 }
70 else
71 {
72 throw new Exception( " 不能连接到打印机! " );
73 }
74 }
75 public bool Close()
76 {
77 return CloseHandle(iHandle);
78 }
79 }
80 }
81
82

 

 

 

转载于:https://www.cnblogs.com/kk1230/archive/2009/11/25/1610728.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值