Showing posts with label win32 api. Show all posts
Showing posts with label win32 api. Show all posts

6.29.2010

GetLastError and FormatMessage and NewLine

When we use FormatMessage to get the system error message by the DWORD(from GetLastError), we will get a LPTSTR that end with NewLine (CRLF). How to convert to be NULL end string? It’s a very easy way to do it:

 

Code Snippet
  1. CString CGetInfo::GetError(void){
  2.     LPVOID lpMsgBuf;
  3.     DWORD dw = GetLastError();
  4.  
  5.     FormatMessage(
  6.         FORMAT_MESSAGE_ALLOCATE_BUFFER |
  7.         FORMAT_MESSAGE_FROM_SYSTEM |
  8.         FORMAT_MESSAGE_IGNORE_INSERTS,
  9.         NULL,
  10.         dw,
  11.         MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
  12.         (LPTSTR) &lpMsgBuf,
  13.         0, NULL );
  14.     CString s = (LPTSTR)lpMsgBuf;
  15.     s.Remove('\r');
  16.     s.Remove('\n');
  17.     return s;
  18. }

當我們在用win32 API裡面的FormatMessage去處理GetLastError傳出來的DWORD 錯誤碼的時候, FormatMessage會回傳一個LPTSTR, 以\r\n結尾的字串, 那怎麼把那個\r\n去掉呢? 其實很簡單, 用CString.Rmove() 兩行輕鬆解決.