P/Invoke call just stops
I'm trying to write data to a serial port via P/Invoke (explicitly not with the SerialPort-class). Here's what I have so far:
[DllImport("kernel32", SetLastError = true)]
static extern IntPtr CreateFile(string filename, // file name
uint desiredAccess, // read? write?
uint shareMode, // sharing
uint attributes, // SecurityAttributes pointer
uint creationDisposition,
uint flagsAndAttributes,
uint templateFile);
[DllImport("kernel32", SetLastError = true)]
static extern bool WriteFile(IntPtr hFile, // handle to file
byte[] lpBuffer, // data buffer
uint nBytesToWrite, // number of bytes to write
out uint nBytesWritten, // number of bytes written
[In] ref NativeOverlapped overlapped); // overlapped buffer
const uint OPEN_EXISTING = 3;
_portHandle = CreateFile("COM1", GENERIC_READ | GENERIC_WRITE, 0, 0, OPEN_EXISTING, 0, 0);
uint bytesWritten;
var buffer = Encoding.ASCII.GetBytes("foo\r");
var overlapped = new NativeOverlapped();
WriteFile(_portHandle, buffer, (uint)buffer.Length, out bytesWritten, ref overlapped);
I get a _portHandle != -1 and can call WriteFile. But after the call, it does nothing. I can wait forever in VS-debug mode and wait for the call to return. Also, no exception is thrown.
Any kernel32开发者_如何学JAVA.dll-masters out there who can help me?
Thanks from Papa Mufflon for introducing that usable project, I derived that for myself and made very simple opensource project from it https://github.com/ebraminio/PInvokeSerialPort that you can also download it from https://nuget.org/packages/PInvokeSerialPort.
Of-course this project is not complete so any suggestion any feature requesting on it is valuable for me :)
Taken Serial Comm from John Hind (http://msdn.microsoft.com/en-us/magazine/cc301786.aspx) instead of developing my own :)
Works great!
精彩评论