开发者

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

开发者 https://www.devze.com 2023-01-21 06:18 出处:网络
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 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.
P开发者_C百科arameter name: handle

I would really appreciate some help. Thanks.


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


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

?

0

精彩评论

暂无评论...
验证码 换一张
取 消