C#编程实现向并口设备发送指令、获取并口设备的状态
usingSystem;
usingSystem.Diagnostics;
usingSystem.Runtime.InteropServices;
usingSystem.Text;
usingSystem.Windows.Forms;
namespaceParallelPort
{
publicpartialclassForm1:Form
{
constuintGENERIC_READ=0x80000000;
constuintGENERIC_WRITE=0x40000000;
constuintFILE_ATTRIBUTE_NORMAL=0x80;
#regionwin32API
[DllImport("kernel32.dll")]
privatestaticexternintCreateFile(
stringlpFileName,
uintdwDesiredAccess,
intdwShareMode,
intlpSecurityAttributes,
intdwCreationDisposition,
uintdwFlagsAndAttributes,
inthTemplateFile
);
[DllImport("kernel32.dll")]
privatestaticexternboolWriteFile(
inthFile,
byte[]lpBuffer,
intnNumberOfBytesToWrite,
refintlpNumberOfBytesWritten,
intlpOverlapped
);
[DllImport("kernel32.dll")]
privatestaticexternboolDefineDosDevice(
intdwFlags,
stringlpDeviceName,
stringlpTargetPath);
[DllImport("kernel32.dll")]
privatestaticexternboolCloseHandle(
inthObject
);
[DllImport("kernel32.dll")]
privatestaticexternboolReadFile(
inthFile,
byte[]lpBuffer,
intnNumberOfBytesToRead,
refintlpNumberOfBytesRead,
intlpOverlapped
);
#endregion
publicForm1()
{
InitializeComponent();
}
privatevoidbutton1_Click(objectsender,EventArgse)
{
intiHandle=-1;
try
{
inti=0;
//创建实例
DefineDosDevice(0x00000001,"LptPortName",@"\Device\Parallel0");
iHandle=CreateFile(@"\\.\LptPortName",GENERIC_READ|GENERIC_WRITE,0,0,3,FILE_ATTRIBUTE_NORMAL,0);
if(iHandle!=-1)
{
byte[]mybyte=newbyte[3]{0x12,0x14,0x14};//要发送的命令(16进制)
WriteFile(iHandle,mybyte,mybyte.Length,refi,0);
byte[]mybyte1=newbyte[3];
stringcontent=String.Empty;
intj=0;
ReadFile(iHandle,mybyte1,3,refj,0);
if(mybyte1!=null)
{
foreach(vartempByteinmybyte1)
{
content+=tempByte.ToString();
}
}
MessageBox.Show(content);//获取的状态值
}
else
{
MessageBox.Show("创建文件失败!");
}
}
catch(Exceptionex)
{
MessageBox.Show(ex.Message);
}
finally
{
if(iHandle>0)
{
CloseHandle(iHandle);
}
}
}
}
}
热门推荐
10 儿子立冬祝福语简短独特
11 对当兵的祝福语简短
12 侄儿高考试祝福语简短
13 伴郎红包祝福语朋友简短
14 媳妇生日简短祝福语朋友
15 公司年会祝福语简短最好
16 元旦感恩祝福语简短大全
17 红包祝福语简短10字
18 周六早晨祝福语简短