今天初次使用MFC来进行网络编程,可以是很痛苦,干了一天才弄出聊天程序的服务器端,现在总结一下今天遇到的主要问题,第一个是::PostMessage方法,这个方法困扰了我好久,该方法的原型是::PostMessage(HWND,msg,WPARAM,LPARAM);HWND是主窗口的句柄,今天我误以为控件的句柄,白忙了大半天,msg是消息,其他两个是参数,这个方法可以在多线程环境下使用,而PostMessage(msg,WPARAM,LPARAM)这个函数必须要依赖一个实体,所以不能在多线程环境下使用。今天遇到的另一个主要问题是乱码问题,现做一下总结:char* 可以直接赋值给CString,CString转换为char的方法是:

WCHAR* temp1 = str.GetBuffer(str.GetLength()+1);
 char* temp = new char[str.GetLength()+1];
 WideCharToMultiByte( CP_ACP, 0, temp1, -1,  
                                    temp, str.GetLength()+1, NULL, NULL );

下面是我从网上copy的一个文章,是关于char*转LPCWSTR的方法总结:

在Windows编程中,经常会碰到字符串之间的转换,char*转LPCWSTR也是其中一个比较常见的转换。下面就列出几种比较常用的转换方法。

1、通过MultiByteToWideChar函数转换

    MultiByteToWideChar函数是将多字节转换为宽字节的一个API函数,它的原型如下:

  1. int MultiByteToWideChar(  
  2.   UINT CodePage,         // code page  
  3.   DWORD dwFlags,         // character-type options  
  4.   LPCSTR lpMultiByteStr, // string to map  
  5.   int cbMultiByte,       // number of bytes in string  
  6.   LPWSTR lpWideCharStr,  // wide-character buffer  
  7.   int cchWideChar        // size of buffer  
  8. );  

LPCWSTR实际上也是CONST WCHAR *类型

 

  1.         char* szStr = "测试字符串";  
  2. WCHAR wszClassName[256];  
  3. memset(wszClassName,0,sizeof(wszClassName));  
  4. MultiByteToWideChar(CP_ACP,0,szStr,strlen(szStr)+1,wszClassName,  
  5.     sizeof(wszClassName)/sizeof(wszClassName[0]));  


2、通过T2W转换宏

  1.         char* szStr = "测试字符串";     
  2. CString str = CString(szStr);  
  3. USES_CONVERSION;  
  4. LPCWSTR wszClassName = new WCHAR[str.GetLength()+1];  
  5. wcscpy((LPTSTR)wszClassName,T2W((LPTSTR)str.GetBuffer(NULL)));  
  6. str.ReleaseBuffer();  


 

3、通过A2CW转换

  1. char* szStr = "测试字符串";     
  2. CString str = CString(szStr);  
  3. USES_CONVERSION;  
  4. LPCWSTR wszClassName = A2CW(W2A(str));  
  5. str.ReleaseBuffer();  


上述方法都是UniCode环境下测试的。