Home >Backend Development >C#.Net Tutorial >Detailed introduction to calling FormatMessage API in C#
FormatMessage is an API provided by WINDOWS. It is used to obtain the text information corresponding to the error code returned when calling the Windows API. It has been used under VB before, but in # I haven't used it in ##C#, mainly because I don't understand some rules of calling Windows API in C#.
Recently, I suddenly became very interested in developing mobile phone programs using VC++ WIN32. I picked up C++ that I haven’t used for a long time. Of course, I need to deal with Windows API frequently. I write too much in C#, and then use VB again. I was a little uncomfortable, so I called this method under C#. Why not use it directly in C++? Well,DWORD WINAPI FormatMessage( in DWORD dwFlags, in LPCVOID lpSource, in DWORD dwMessageId, in DWORD dwLanguageId, out LPTSTR lpBuffer, in DWORD nSize, in va_list* Arguments );
const int FORMAT_MESSAGE_FROM_SYSTEM = 0x1000; const int FORMAT_MESSAGE_IGNORE_INSERTS = 0x200; [DllImport("Kernel32.dll")] private static extern int FormatMessage(uint dwFlags, IntPtr lpSource, uint dwMessageId, uint dwLanguageId, [Out]StringBuilder lpBuffer, uint nSize, IntPtr arguments);This is the FormatMessage API prototype and definition in C#. The second and last parameters are not used, so they can be defined as IntPtr or int. If it is int, 0 is passed in when calling. For IntPtr, pass in IntPtr.Zero. What’s annoying is that the lpBuffer parameter is used to receive the returned text information. In VB, this type of parameter is defined as ByVal String, and then initialized with Space (length) (put
StringInitialized to a space of specified length), just specify the length value for nSize when calling.
In a similar method in C#, the parameters are defined as String LPBUFFER. When calling, when calls,:
uint dwFlags= FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS ; string lpBuffer=new string(' ',260); int count=FormatMessage(dwFlags,IntPtr.Zero,1439,0,lpBuffer,260,IntPtr.Zero);can be known by the return value. The value has not changed. Later, the processing of string in C#was similar to C. It was treated as a
constant
to the processing. Modify the value of a string A new string. Obviously the output parameter cannot be defined as a string here.The last change to stringbuilder, and use [OUT] Properties
to be modified. When calling, when you call,:
StringBuilder lpBuffer=new StringBuilder(260); //声明StringBuilder的初始大小 int count=FormatMessage(dwFlags,IntPtr.Zero,1439,0,lpBuffer,260,IntPtr.Zero);Success!
The above is the detailed content of Detailed introduction to calling FormatMessage API in C#. For more information, please follow other related articles on the PHP Chinese website!