问题
I am writing a C# .NET 2.0 application wherein when a message is expected to be received via the SerialPort
. If the frame is not received (i.e. times out) or it is determined to be invalid, I need to set an error code using SetLastError
. Windows has a plethora of error codes. Is there a simple tool or reference to help narrow down the proper error code to use?
ADDITIONAL INFO
While throwing an exception and handling it higher up the stack is my preference, that is not an option in this case because the application I am updating was not designed to take advantage of such a useful feature.
回答1:
in the "good old days" (C and C++), the list of possible Windows errors was defined in winerror.h
UPDATE: Link below is dead. Not sure if the file is still available for download, but all the Windows System Error Code definitions can be found at this link.
This file can be found on Microsoft's site (although it surprises me a little that it is dated as far back as 2003 - might be worth hunting for a more recent version).
But if you're getting (or wanting to set) Win32 error codes, this'll be where the definition is found.
回答2:
Unfortunately the above didn't work for me, however this worked perfectly for me, pasting the whole code so it can be copy pasted directly in C#
public static class WinErrors
{
/// <summary>
/// Gets a user friendly string message for a system error code
/// </summary>
/// <param name="errorCode">System error code</param>
/// <returns>Error string</returns>
public static string GetSystemMessage(uint errorCode)
{
var exception = new Win32Exception((int)errorCode);
return exception.Message;
}
}
回答3:
using System.Runtime.InteropServices; // DllImport
public static string GetSystemMessage(int errorCode) {
int capacity = 512;
int FORMAT_MESSAGE_FROM_SYSTEM = 0x00001000;
StringBuilder sb = new StringBuilder(capacity);
FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, IntPtr.Zero, errorCode, 0,
sb, sb.Capacity, IntPtr.Zero);
int i = sb.Length;
if (i>0 && sb[i - 1] == 10) i--;
if (i>0 && sb[i - 1] == 13) i--;
sb.Length = i;
return sb.ToString();
}
[DllImport("kernel32.dll")]
public static extern int FormatMessage(int dwFlags, IntPtr lpSource, int dwMessageId,
int dwLanguageId, StringBuilder lpBuffer, int nSize, IntPtr Arguments);
回答4:
You can find a list of them all here:
http://en.kioskea.net/faq/2347-error-codes-in-windows
Then just do a search for 'Serial' and use whichever one best fits your error
来源:https://stackoverflow.com/questions/3823888/how-do-i-look-up-the-proper-windows-system-error-code-to-use-in-my-application