P / Invoke call stops

I am trying to write data to a serial port through P / Invoke (obviously not with the SerialPort class). Here is what I still have:

[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 _portHandle! = -1 and can call WriteFile. But after the call, he does nothing. I can wait in VS-debug mode and wait for the call to return. In addition, an exception is not thrown.

Any kernel32.dll host that can help me?

+4
source share
2 answers

Taken by Serial Comm from John Hind (http://msdn.microsoft.com/en-us/magazine/cc301786.aspx) instead of creating your own :)

It works great!

0
source

Thanks from Papa Mufflon for presenting this useful project, I got it for myself and made it a very simple open source project https://github.com/ebraminio/PInvokeSerialPort , which you can also download from https: //nuget.org/packages/PInvokeSerialPort .

Of course, this project is not complete, so any proposal requesting it is valuable to me :)

+2
source

All Articles