2013-04-15 5 views
0

USB HID 장치에 쓰려고합니다.USB HID 장치에 쓸 수 없습니다.

내 32 비트 XP에서 작동하는 데 사용되는 코드 만 불량에 대해 내가 64 비트에 노력하고있어 윈도우 7 나는 장치를 찾으 경로의 수, 이것은하여 FileStream에 대한 핸들 & 패스를 엽니 다 CreateFile Win32 API 함수를 사용할 수 있습니다. 지금까지 모든 것이 잘 보입니다. 그런 다음 데이터를 스트림 &에 쓰고 USB 장치가 아무 작업도 수행하지 않습니다.

내가 무엇을하지 않고 있는지 알 수있는 방법은 무엇입니까? & 그런 다음 어떻게하면 좋을까요?

[DllImport("kernel32.dll", SetLastError = true)] 
    public static extern SafeFileHandle CreateFile(
     [MarshalAs(UnmanagedType.LPStr)] string name, 
     uint access, 
     int shareMode, 
     IntPtr security, 
     int creationFlags, 
     int attributes, 
     IntPtr template); 

함수를 호출 : 장치로하여 FileStream 열기

var handle = usb.Win32Wrapper.CreateFile(path, usb.Win32Wrapper.GENERIC_READ | usb.Win32Wrapper.GENERIC_WRITE, 0, IntPtr.Zero, usb.Win32Wrapper.OPEN_EXISTING, usb.Win32Wrapper.FILE_FLAG_OVERLAPPED, IntPtr.Zero); 

:

_main = new FileStream(handle, FileAccess.Write, 1, true); 

마지막으로 파일에 쓰는 :

이 내 수입 서명입니다

_main.Write(buffer,0,buffer.Length); 
+0

시도 보고 [이 스레드] (http://social.msdn.microsoft.com/Forums/en-US/csharpgeneral/thread/44ca52eb-a51e-4614-aeb9-fb072d4dab82/) – Icemanind

+0

흥미 롭 군. CreateFile을 호출 할 때 오류가 발생하지 않으며 HID 장치가 디스크로 표시되지 않지만 계속 진행할 것입니다. –

+0

불행히도 아무런 차이가 없었습니다. 중복 된 IO 플래그도 제거하려고했습니다. 아무런 차이가 없었습니다. –

답변

1

기기의 특성을 모른 채 말하기가 어렵습니다.

기기 (hidapi, HIDSharp 등)와 통신 할 수 있는지 확인 했습니까? USB HID 장치가 시간이 끝날 때까지 NAK로 응답 할 수 없다는 것은 아무 것도 없습니다.이 경우 전송이 끝나지 않습니다.

내가 먼저 (내가 잠시 동안 윈도우 7을 사용하고, 그래서 XP가 동일한 제한이있는 경우 내가 말할 수 없다) HID를 통해 통신 할 때 퉜다 문제 :

(1) 보고서 ID 바이트를 포함해야합니다. 장치에서 지원하지 않더라도 Windows는 0의 보고서 ID가 필요합니다.

(2) Windows에서 버퍼는 최대 보고서와 길이가 같아야합니다. 예를 들어 보고서가 48 바이트 인 경우 49 바이트 (보고서 ID로 시작)를 작성해야합니다. 내가 이것을하지 않으면 쓰기 오류가 발생하는 것을 기억하는 것 같습니다.

당신은 언급하기 때문에 64 비트 Windows ...

(3) 나는 우연히 한 64 비트 Windows 특정 문제였습니다 64 비트 P/호출 (.NET 2.0의 같은 4.0) OVERLAPPED 구조체 (또는 그 문제에 대해 NativeOverlapped)는 blittable로 취급하지 않습니다. 따라서 'ref OVERLAPPED'를 사용하면 복사, P/Invoke 및 복사가 수행됩니다. 겹쳐진 연산은 메모리가 움직이지 않는다고 가정하므로 실제 문제입니다. GetOverlappedResult가 잘못되었거나 미묘한 메모리 손상 등이 있습니다. fixed() 또는 stackalloc로 해결할 수 있습니다. 구조체가 스택에 할당 된 경우에도 reminder ref T는 T *와 동일하지 않습니다.

이 세 가지 중 하나 이상으로 문제가 해결되기를 바랍니다.:)

제임스

+0

유용합니다. 이 코드는 32 비트 XP에서 작동했습니다. HID 장치는 실제로 복합체이므로 두 인터페이스에 대한 핸들을 얻고 보고서의 크기를 계산하고 각 인터페이스에 적절한 메시지를 보냅니다. –

+0

1GB 버퍼 크기가 문제가 될지 궁금합니다. FileStream이 보고서 크기보다 작은 청크로 WriteFile을 호출하면 Windows는 그런 것을 좋아하지 않습니다. – Zer

+0

"보고서 ID = 0"이 매우 중요합니다. 보고서 크기를 64로 정의한다고 가정하면, 실제 배열은'hid_out [65]'와'hid_out [0] = 0' 일 필요가 있습니다. –

-1

------------------------------- 인쇄 바코드 ------ ---------

private int PrintBarcode(string barcode, string printFormat, int printCount) 
    { 
     string text = "B400,50,1,1,2,1,150,B,"; 
     if (printFormat != null) 
     { 
      text = printFormat; 
     } 
     string barcod = string.Concat(new object[] 
     { 
      text, 
      Convert.ToChar(34), 
      barcode, 
      Convert.ToChar(34), 
      "\n" 
     }); 

     string printerName= ConfigurationManager.AppSettings["PrinterName"]; 

     int x = 100; 
     int y = 0; 
     using (EtiquetaTestCommand1 etiquetaTestCommand = new EtiquetaTestCommand1(new Size(500, 750), 19, new Point(x, y), printCount, barcod)) 
     { 
      string commandString = ((ICommand)etiquetaTestCommand).GetCommandString(); 


      //var sb1 = new StringBuilder(); 
      // sb1.AppendLine(); 
      // sb1.AppendLine("N"); 
      // sb1.AppendLine("Q750,19"); 
      // sb1.AppendLine("q500"); 
      // sb1.AppendLine("R100,0"); 
      // sb1.AppendLine(barcod); 
      // sb1.AppendLine("P1"); 

      RawPrinterHelper.SendStringToPrinter(printerName, commandString.ToString()); 


     } 

---------------------------------- 예제 테스트 명령 --------------------------

internal sealed class EtiquetaTestCommand1 : Label, IDisposable 
{ 
    private Bitmap _bmp; 

    internal EtiquetaTestCommand1(Size size, int gapLength, Point referencePoint, int numberCopies, string barcod) : base(size, gapLength, referencePoint, numberCopies, barcod) 
    { 
     int x = 5; 
     int y = 5; 
     ((IComplexCommand)this).AddCommand(BarCodeCommand.Code128ModeABarCodeCommand(x, y, barcod)); 
    } 

    ~EtiquetaTestCommand1() 
    { 
     this.Dispose(false); 
    } 

    private void Dispose(bool disposing) 
    { 
     if (disposing) 
     { 
     } 
    } 

    void IDisposable.Dispose() 
    { 
     this.Dispose(true); 
    } 
} 

---------------- ------ PrinterName ---------------

<add key="PrinterName" value="ZDesigner LP 2844"/> 

----------------- SendStringToPrinter ----------------------

public class RawPrinterHelper 
    { 
     // Structure and API declarions: 
     [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)] 
     public class DOCINFOA 
     { 
      [MarshalAs(UnmanagedType.LPStr)] 
      public string pDocName; 
      [MarshalAs(UnmanagedType.LPStr)] 
      public string pOutputFile; 
      [MarshalAs(UnmanagedType.LPStr)] 
      public string pDataType; 
     } 
     [DllImport("winspool.Drv", EntryPoint = "OpenPrinterA", SetLastError = true, CharSet = CharSet.Ansi, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)] 
     public static extern bool OpenPrinter([MarshalAs(UnmanagedType.LPStr)] string szPrinter, out IntPtr hPrinter, IntPtr pd); 

     [DllImport("winspool.Drv", EntryPoint = "ClosePrinter", SetLastError = true, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)] 
     public static extern bool ClosePrinter(IntPtr hPrinter); 

     [DllImport("winspool.Drv", EntryPoint = "StartDocPrinterA", SetLastError = true, CharSet = CharSet.Ansi, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)] 
     public static extern bool StartDocPrinter(IntPtr hPrinter, Int32 level, [In, MarshalAs(UnmanagedType.LPStruct)] DOCINFOA di); 

     [DllImport("winspool.Drv", EntryPoint = "EndDocPrinter", SetLastError = true, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)] 
     public static extern bool EndDocPrinter(IntPtr hPrinter); 

     [DllImport("winspool.Drv", EntryPoint = "StartPagePrinter", SetLastError = true, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)] 
     public static extern bool StartPagePrinter(IntPtr hPrinter); 

     [DllImport("winspool.Drv", EntryPoint = "EndPagePrinter", SetLastError = true, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)] 
     public static extern bool EndPagePrinter(IntPtr hPrinter); 

     [DllImport("winspool.Drv", EntryPoint = "WritePrinter", SetLastError = true, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)] 
     public static extern bool WritePrinter(IntPtr hPrinter, IntPtr pBytes, Int32 dwCount, out Int32 dwWritten); 

     // SendBytesToPrinter() 
     // When the function is given a printer name and an unmanaged array 
     // of bytes, the function sends those bytes to the print queue. 
     // Returns true on success, false on failure. 
     public static bool SendBytesToPrinter(string szPrinterName, IntPtr pBytes, Int32 dwCount) 
     { 
      Int32 dwError = 0, dwWritten = 0; 
      IntPtr hPrinter = new IntPtr(0); 
      DOCINFOA di = new DOCINFOA(); 
      bool bSuccess = false; // Assume failure unless you specifically succeed. 

      di.pDocName = "My C#.NET RAW Document"; 
      di.pDataType = "RAW"; 

      // Open the printer. 
      if (OpenPrinter(szPrinterName.Normalize(), out hPrinter, IntPtr.Zero)) 
      { 
       // Start a document. 
       if (StartDocPrinter(hPrinter, 1, di)) 
       { 
        // Start a page. 
        if (StartPagePrinter(hPrinter)) 
        { 
         // Write your bytes. 
         bSuccess = WritePrinter(hPrinter, pBytes, dwCount, out dwWritten); 
         EndPagePrinter(hPrinter); 
        } 
        EndDocPrinter(hPrinter); 
       } 
       ClosePrinter(hPrinter); 
      } 
      // If you did not succeed, GetLastError may give more information 
      // about why not. 
      if (bSuccess == false) 
      { 
       dwError = Marshal.GetLastWin32Error(); 
      } 
      return bSuccess; 
     } 

     public static bool SendFileToPrinter(string szPrinterName, string szFileName) 
     { 
      // Open the file. 
      FileStream fs = new FileStream(szFileName, FileMode.Open); 
      // Create a BinaryReader on the file. 
      BinaryReader br = new BinaryReader(fs); 
      // Dim an array of bytes big enough to hold the file's contents. 
      Byte[] bytes = new Byte[fs.Length]; 
      bool bSuccess = false; 
      // Your unmanaged pointer. 
      IntPtr pUnmanagedBytes = new IntPtr(0); 
      int nLength; 

      nLength = Convert.ToInt32(fs.Length); 
      // Read the contents of the file into the array. 
      bytes = br.ReadBytes(nLength); 
      // Allocate some unmanaged memory for those bytes. 
      pUnmanagedBytes = Marshal.AllocCoTaskMem(nLength); 
      // Copy the managed byte array into the unmanaged array. 
      Marshal.Copy(bytes, 0, pUnmanagedBytes, nLength); 
      // Send the unmanaged bytes to the printer. 
      bSuccess = SendBytesToPrinter(szPrinterName, pUnmanagedBytes, nLength); 
      // Free the unmanaged memory that you allocated earlier. 
      Marshal.FreeCoTaskMem(pUnmanagedBytes); 
      return bSuccess; 
     } 
     public static bool SendStringToPrinter(string szPrinterName, string szString) 
     { 
      IntPtr pBytes; 
      Int32 dwCount; 
      // How many characters are in the string? 
      dwCount = (szString.Length + 1) * Marshal.SystemMaxDBCSCharSize; 
      // Assume that the printer is expecting ANSI text, and then convert 
      // the string to ANSI text. 
      pBytes = Marshal.StringToCoTaskMemAnsi(szString); 
      // Send the converted ANSI string to the printer. 
      SendBytesToPrinter(szPrinterName, pBytes, dwCount); 
      Marshal.FreeCoTaskMem(pBytes); 
      return true; 
     } 
    } 
+0

질문자가 놓친 의견과 해결책이 나오는 이유를 추가해주십시오. 감사. –

관련 문제