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
助けていただければ幸いです。ありがとう。