Reputation: 5480
I'm trying to write to a USB HID device.
My code used to work on 32bit XP, but for badness I'm trying on 64bit Windows 7. I can find the device, get it's path, use CreateFile
win32 API function to open a handle & pass this to FileStream. Everything seems fine so far. I then write the data to the stream & the USB device does nothing.
How can I find out why it's not doing anything & then hopefully make it do something?
This is my import signature:
[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);
Calling the function:
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);
Opening the FileStream to the device:
_main = new FileStream(handle, FileAccess.Write, 1, true);
and finally writing to the file:
_main.Write(buffer,0,buffer.Length);
Upvotes: 0
Views: 7588
Reputation: 1
-------------------------------PRİNT BARCODE---------------
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());
}
----------------------------------EtiquetaTestCommand1 --------------------------
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;
}
}
Upvotes: -1
Reputation: 1904
It's hard to say without knowing the specifics of your device.
Have you confirmed you can communicate with the device (hidapi, HIDSharp, etc.)? There's nothing saying a USB HID device can't reply with NAKs until the end of time, in which case your send will never finish.
The issues I ran into when I first trying to communicate over HID (I've been using Windows 7 for a while, so I can't say if XP has the same restrictions):
(1) Make sure you include a Report ID byte. Even if your device does not support one, Windows needs a Report ID of 0.
(2) On Windows your buffer needs to be the same length as the maximum report. So for example, if your report is 48 bytes, you need to write 49 bytes (start with a Report ID always). I seem to recall getting a write error if I didn't do this.
Since you mention 64-bit Windows...
(3) One 64-bit Windows specific issue I ran into was that (as of .NET 2.0 and 4.0) 64-bit P/Invoke does not treat the OVERLAPPED structure (or NativeOverlapped for that matter) as blittable. Therefore if you use 'ref OVERLAPPED' it will make a copy, P/Invoke, and copy back. Overlapped operations assume the memory doesn't move, so this is a real problem -- GetOverlappedResult will be flat-out wrong, you'll get subtle memory corruption, etc. You can solve this with fixed() or stackalloc -- it's one reminder ref T isn't identical to T*, even if the struct is allocated on the stack.
Hope at least one of these three resolves your problem. :)
James
Upvotes: 2