C#引入WINAPI传递中文字符串参数字符集问题

C#引入WINAPI传递中文字符串参数字符集问题

C#可以通过DllImport引入WinAPI。完整的引入语句包含dll文件名(路径),CharSet字符集,EntryPoint函数入口,SetLastError是否在调用前设置WinAPI函数SetLastError值

   [DllImport("user32.dll", CharSet = CharSet.Auto, EntryPoint = "MessageBox", SetLastError=false)]    
   public static extern int MyMessageBox(IntPtr hWnd, String text, String caption, uint type); 

CharSet默认值是并不是CharSet.Auto,而是CharSet.Ansi

WinAPI函数的字符串参数所用字符集在不同版本的Windows系统并不统一,XP以前的系统通常是Ansi字符集,Windows7和NT系统是Unicode字符集。通常使用CharSet.Auto参数,让系统自动选择总是没错的(但不知道默认参数为什么不是CharSet.Auto),除非你指定调用AbcW宽字符集或AbcA窄字符集的函数版本。
如果你没有指定CharSet,系统默认使用CharSet.Ansi,如果传递中文字符串,大概率是会调用失败,或者出现乱码的。

猜你喜欢

转载自blog.csdn.net/qq_31042143/article/details/125906854
今日推荐