SetCommState fail to work in c#! Help!

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Hi there,

SetCommState fail to work in C#, i keep gettting the error of 87, invalid
parameter.

I use this GetLastError to get the value 87.

There is a difference between GetLastError and GetLastWin32Error

Marshal.GetLastWin32Error - returns 0 (means fail to open)

[DllImport("kernel32.dll")]
internal static extern uint GetLastError(); - returns 87 (invalid parameter)

But i did the same thing for SetCommState

[DllImport("kernel32.dll")]
internal static extern bool SetCommState(IntPtr hFile, [In] ref Dcb lpDcb);

Wonder why it fails? GetCommState and others works pretty fine!

I had updated the Dcb structures values when i debug it, and past into the
functions, and it dies off! Why?

C programming works fine not C#.

Any help? Thanks.
 
I use this GetLastError to get the value 87.

You can't call GetLastError from managed code, so the error code it
returns is irrelevant.

Marshal.GetLastWin32Error is the right way to do it. You must also set
SetLastError=true in the DllImport attribute for the function.

Wonder why it fails?

That's impossible to say without seeing your code.



Mattias
 
Dear Mattias,

Yeah, i had modified like what you had suggested. I still receive 87, no
difference with GetLastWin32Error.

But i am wondering:

Can't work:

if (!ClassA.SetCommState(instStruct.handle, ref instStruct.port[0].dcb))
{
Debug.WriteLine(Marshal.GetLastWin32Error());

}

Can work:

if (ClassA.SetCommState(instStruct.handle, ref instStruct.port[0].dcb))
{
Debug.WriteLine(Marshal.GetLastWin32Error());

}

But if most of my codes, i use ! in front of the function, if return false,
will throw an exception. But why the 2nd one without the ! works fine? No
more error 87.

Any idea?

Thanks.
 
Back
Top