تقييم الموضوع :
  • 0 أصوات - بمعدل 0
  • 1
  • 2
  • 3
  • 4
  • 5
لمعرفة رسالة الخطأ الأخيرة بعد استدعاء دالة API (Last Error Message)
#1
كاتب الموضوع : Boutemine Oualid


كود :
// using System.Runtime.InteropServices;
[ DllImport( "kernel32.dll", CharSet = CharSet.Auto/*, SetLastError = true */ ) ]
private static extern uint FormatMessage
(
uint dwFlags,
IntPtr lpSource,
uint dwMessageId,
uint dwLanguageId,
ref IntPtr lpBuffer,
uint nSize,
IntPtr Arguments
);
public string GetLastWin32ErrorMessage( )
{
return GetLastWin32ErrorMessage( Marshal.GetLastWin32Error( ) );
}
public string GetLastWin32ErrorMessage( int errorCode )
{
IntPtr buffer = IntPtr.Zero;
uint cnt = FormatMessage
(
0x00000100 | // FORMAT_MESSAGE_ALLOCATE_BUFFER
0x00000200 | // FORMAT_MESSAGE_IGNORE_INSERTS
0x00001000, // FORMAT_MESSAGE_FROM_SYSTEM
IntPtr.Zero,
( uint )errorCode,
0, // LANGIDs : Neutral, Thread, User, System, en-US
ref buffer,
0,
IntPtr.Zero
);
if ( cnt == 0 || buffer == IntPtr.Zero )
return String.Format( "Unknown error: {0}.", errorCode );
string errorMessage = Marshal.PtrToStringAuto( buffer, ( int )cnt );
Marshal.FreeHGlobal( buffer ); // LocalFree.
return errorMessage;
}
VB.NET

كود :
<DllImport("kernel32.dll")> _
Public Function FormatMessage(ByVal dwFlags As Integer, ByRef lpSource As IntPtr, _
ByVal dwMessageId As Integer, ByVal dwLanguageId As Integer, ByRef lpBuffer As [String], _
ByVal nSize As Integer, ByRef Arguments As IntPtr) As Integer
End Function
Public Function GetErrorMessage(ByVal errorCode As Integer) As String
Dim FORMAT_MESSAGE_ALLOCATE_BUFFER As Integer = &H100
Dim FORMAT_MESSAGE_IGNORE_INSERTS As Integer = &H200
Dim FORMAT_MESSAGE_FROM_SYSTEM As Integer = &H1000
Dim msgSize As Integer = 255
Dim lpMsgBuf As String
Dim dwFlags As Integer = FORMAT_MESSAGE_ALLOCATE_BUFFER Or FORMAT_MESSAGE_FROM_SYSTEM Or FORMAT_MESSAGE_IGNORE_INSERTS
Dim lpSource As IntPtr = IntPtr.Zero
Dim lpArguments As IntPtr = IntPtr.Zero
'Call the FormatMessage function to format the message.
Dim returnVal As Integer = FormatMessage(dwFlags, lpSource, errorCode, 0, lpMsgBuf, _
msgSize, lpArguments)
If returnVal = 0 Then
Throw New Exception("Failed to format message for error code " + errorCode.ToString() + ". ")
End If
Return lpMsgBuf
End Function
}}}
تم الشكر بواسطة:



التنقل السريع :


يقوم بقرائة الموضوع: بالاضافة الى ( 1 ) ضيف كريم