Cannot open LPT1(Printer Port) on win7 (64bit). The same applicaion works on win XP

女生的网名这么多〃 提交于 2019-12-12 10:05:24

问题


I have an application that opens a port to a printer(it's a bar code printer) which works on win XP but when i switch to win7 (64bit) i have a problem. Here is the code:

I am using this method to open the port:

        [DllImport("kernel32.dll", SetLastError = true)]
        public static extern SafeFileHandle CreateFile(
           String pipeName,
           uint dwDesiredAccess,
           uint dwShareMode,
           IntPtr lpSecurityAttributes,
           uint dwCreationDisposition,
           uint dwFlagsAndAttributes,
           IntPtr hTemplate);

and i call it like this:

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

What happens is that pipeHandle.Close=false and pipeHandle.IsInvalid=true

This is the method that sends data to the port

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

and i get the exception:

ArgumentException
Invalid handle.
Parameter name: handle

I would really appreciate some help. Thanks.


回答1:


Have you tried running the executable in WinXP compatability-mode? It could have some trouble with the new Windows driver model in Windows 7.




回答2:


What portName you've specified ? Have you tried:

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

?



来源:https://stackoverflow.com/questions/4003788/cannot-open-lpt1printer-port-on-win7-64bit-the-same-applicaion-works-on-win

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!