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);
}
}
}
}
}