C#调用 WIN32 API 的 string 类型是ANSI版本?

谁学逆向工程 2016-09-07 01:28:40
我在学习如何在C#中调用 WIN32 API,下面用 MessageBox 函数进行尝试。学过C/C++的人知道 API 有两个版本,一个是W 版本一个是A版本。
比如 MessageBox 就是个宏定义,其背后的函数是 MessageBoxA 或者 MessageBoxW。我运行下面的W版本函数显示的是乱码,而运行A版本显示正常的。
如何才能正常使用 W 版本函数呢?


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using System.Drawing;
using System.Windows.Forms;
using System.Threading;
using System.Drawing.Printing;
using System.Drawing.Drawing2D;
using System.Runtime.InteropServices;
class HelloPrinter : Form
{
public static void Main()
{
Application.Run(new HelloPrinter());
}
[DllImport("user32.dll")]
public static extern int MessageBoxW(IntPtr hWnd, string text, string caption, uint type);
protected override void OnKeyPress(KeyPressEventArgs e)
{
string text = "text文本字符串";
string caption = "caption标题栏";
MessageBoxW(Handle, text, caption, 0);
}
}

...全文
70 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
Poopaye 2016-09-07
  • 打赏
  • 举报
回复
[DllImport("user32.dll", CharSet = CharSet.Unicode)]
mwp 2016-09-07
  • 打赏
  • 举报
回复
c#里的string类型是需要转换后才能用到C++里的(封送),这个转换就涉及编码类型的问题,默认是Ansi,所以调用就出了乱码, [DllImport("user32.dll", CharSet = CharSet.Unicode)] public static extern int MessageBoxW(IntPtr hWnd, string text, string caption, uint type); 你这样写就没问题了。

110,533

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧