2

我有一个应用程序可以打开一个打印机端口(它是一个条形码打印机),它可以在 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

我真的很感激一些帮助。谢谢。

4

2 回答 2

0

portName指定了什么?你有没有尝试过:

pipeHandle = CreateFile("NONSPOOLED_LPT1", GENERIC_READ | GENERIC_WRITE, 0, IntPtr.Zero, OPEN_EXISTING, FILE_FLAG_OVERLAPPED, IntPtr.Zero);

?

于 2010-10-24T08:53:33.713 回答
0

您是否尝试过在 WinXP 兼容模式下运行可执行文件?Windows 7 中的新 Windows 驱动程序模型可能会出现一些问题。

于 2010-10-23T11:49:49.553 回答