1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
|
private void btnGetMessage_Click(object sender, EventArgs e)
{
string strMessage;
strMessage = GetErrorMessage(1326);
MessageBox.Show(strMessage);
}
[DllImport("kernel32.dll", CharSet = System.Runtime.InteropServices.CharSet.Auto)]
private unsafe static extern int FormatMessage(int dwFlags, ref IntPtr pMessageSource, int dwMessageID, int dwLanguageID, ref string lpBuffer, int nSize, IntPtr* pArg);
private unsafe static string GetErrorMessage(int errorCode)
{
int FMT_ALLOCATE_BUFFER = 0x00000100;
int FMT_IGNORE_INSERTS = 0x00000200;
int FMT_FROM_SYSTEM = 0x00001000;
int minBufferSize = 0;
string messageBuffer = String.Empty;
string message = String.Empty;
int dwFlags = FMT_FROM_SYSTEM | FMT_ALLOCATE_BUFFER | FMT_IGNORE_INSERTS;
// Initialize pointers.
IntPtr pMessageSource = new IntPtr();
IntPtr pArgs = new IntPtr();
CultureInfo currentCulture = CultureInfo.CurrentCulture;
currentCulture = new CultureInfo("en-US");
int pid = PRIMARYLANGID(currentCulture.LCID);
int sid = SUBLANGID(currentCulture.LCID);
int langID = MAKELANGID(pid, sid);
int messageSize = 0;
messageSize = FormatMessage(dwFlags, ref pMessageSource, errorCode, langID, ref messageBuffer, minBufferSize, &pArgs);
if (messageSize == 0)
{
string messages = new Win32Exception(Marshal.GetLastWin32Error()).Message;
MessageBox.Show(messages);
}
message = String.Format("{0}", messageBuffer);
return message;
}
public static int MAKELANGID(int primary, int sub)
{
return (((ushort)sub) << 10) | ((ushort)primary);
}
public static int PRIMARYLANGID(int lcid)
{
return ((ushort)lcid) & 0x3ff;
}
public static int SUBLANGID(int lcid)
{
return ((ushort)lcid) >> 10;
} |
Partager