我有一个应用程序可以打开一个打印机端口(它是一个条形码打印机),它可以在 win XP 上运行,但是当我切换到 win7(64 位)时我遇到了问题。这是代码:
我正在使用这种方法打开端口:
[DllImport("kernel32.dll", SetLastError = true)]
public static extern SafeFileHandle CreateFile(
String pipeName,
uint dwDesiredAccess,
uint dwShareMode,
IntPtr lpSecurityAttributes,
uint dwCreationDisposition,
uint dwFlagsAndAttributes,
IntPtr hTemplate);
我这样称呼它:
public void OpenPort(String portName)
{
if (String.IsNullOrEmpty(m_portName)) throw new Exception(SET_PORTNAME);
this.m_portName = portName;
pipeHandle = CreateFile(portName, GENERIC_READ | GENERIC_WRITE, 0, IntPtr.Zero,
OPEN_EXISTING, FILE_FLAG_OVERLAPPED, IntPtr.Zero);
}
会发生什么 pipeHandle.Close=false 和 pipeHandle.IsInvalid=true
这是向端口发送数据的方法
private void WriteBytesToPrinter(byte[] dataBytes)
{
if (!IsPortOpen) throw new Exception(OPEN_PORT_ERROR);
using (FileStream fStream = new FileStream(pipeHandle, FileAccess.Write,
dataBytes.Length, true))
{
fStream.Write(dataBytes, 0, dataBytes.Length);
fStream.Flush();
fStream.Close();
}
}
我得到了例外:
ArgumentException
Invalid handle.
Parameter name: handle
我真的很感激一些帮助。谢谢。