日期:2014-05-17  浏览次数:20976 次

C#调用win32 api宽字符版函数出乱码,如何解决?
本帖最后由 u012000298 于 2013-09-06 12:53:13 编辑
.net framework内部是用Unicode对吧?
我下面这个小程序可以显示一个对话框,

using System.Runtime.InteropServices;
namespace cs_ConsoleApplication1
{
    class Program
    {
        [DllImport("user32.dll", EntryPoint="MessageBox")]
        public static extern int MessageBoxA(IntPtr hWnd, String text, String caption, uint type);

        static void Main(string[] args)
        {
            MessageBoxA(new IntPtr(0), "Hello!", "caption", 0);
        }
    }
}

可以显示:

看起来没有问题。如果我把代码改成调用MessageBoxW,反而不能工作了,显示乱码:

using System.Runtime.InteropServices;
namespace cs_ConsoleApplication1
{
    class Program
    {
        [DllImport("user32.dll", EntryPoint="MessageBoxW")]
        public static extern int MessageBoxW(IntPtr hWnd, String text, String caption, uint type);

        static void Main(string[] args)
        {
            MessageBoxW(new IntPtr(0), "Hello!", "caption", 0);
        }
    }
}


Ansi版本的反而能工作,W版本的反而不能工作? 我期待的是只有W能正常工作,而实际和我预期的正好相反。
这是为什么呢? 

------解决方案--------------------
[DllImport("user32.dll", EntryPoint="MessageBoxW",CharSet=CharSet.Unicode)]
public static extern int MessageBox