如何使用 Declare 语句导入 user32.dll 中的 MessageBox 函数?

解读

国内 Windows 桌面开发面试常把“会不会调 Win32 API”当成 VB6 老项目维护与 VB.NET 互操作能力的分水岭。
Declare 语句是 VB 系列语言访问外部 DLL 的唯一入口,写错一处就会直接 Runtime Error ‘48’“找不到 .dll”或 ‘49’“错误的 DLL 调用约定”。
面试官想确认三点:

  1. 语法格式是否背得准(Alias、Lib、CallingConvention、Charset);
  2. 参数类型能不能一一对应 Win32 原型(尤其是 32/64 位句柄宽度、字符串编码);
  3. 是否知道 VB6 与 VB.NET 在 Declare 上的差异,避免把 ANSI 版直接搬进 .NET 造成乱码或崩溃。

知识点

  1. Declare 语句结构:
    [Public|Private] Declare [Ansi|Unicode|Auto] Function|Sub 名称 Lib "dll" [Alias "别名"] (参数列表) [As 返回类型]
  2. 调用约定:Win32 API 缺省是 stdcall,VB6 只能识别 stdcall;VB.NET 可追加 CharSet 与 ExactSpelling 修饰。
  3. 数据映射:Long 在 VB6 是 32 位带符号整数,对应 C 的 int;在 VB.NET Long 是 64 位,必须用 Integer(32 位)或 IntPtr 才能匹配 HWND。
  4. 字符串:VB6 默认 ANSI,需用 ByVal String 并确保 DLL 入口是 CharSetA;VB.NET 推荐 Unicode,入口为 MessageBoxW。
  5. 错误处理:VB6 用 Err.LastDllError;VB.NET 用 Marshal.GetLastWin32Error(),且需追加 SetLastError:=True。

答案

  1. VB6 写法(ANSI 版,兼容 Windows 95 以后所有系统)
Private Declare Function MessageBox Lib "user32" Alias "MessageBoxA" _
        (ByVal hWnd As Long, _
         ByVal lpText As String, _
         ByVal lpCaption As String, _
         ByVal wType As Long) As Long

'调用示例
Sub Test()
    Dim ret As Long
    ret = MessageBox(0, "你好,VB6!", "提示", vbInformation Or vbOKOnly)
End Sub

要点:

  • Alias "MessageBoxA" 明确指定 ANSI 入口;
  • 四个参数全部 ByVal,句柄 hWnd 用 Long(32 位);
  • 返回值为 Long,表示被按下的按钮 ID。
  1. VB.NET 写法(Unicode,推荐 2005 以后语法)
Imports System.Runtime.InteropServices

Public Class Win32
    <DllImport("user32.dll", CharSet:=CharSet.Unicode, SetLastError:=True, ExactSpelling:=True)>
    Public Shared Function MessageBox(hWnd As IntPtr,
                                      lpText As String,
                                      lpCaption As String,
                                      uType As UInteger) As Integer
    End Function
End Class

'调用
Win32.MessageBox(IntPtr.Zero, "你好,VB.NET!", "提示", &H40 Or &H0)

要点:

  • 用 Integer(32 位)对应 C int,IntPtr 承载 HWND,保证 32/64 位通用;
  • CharSet.Unicode 自动入口 MessageBoxW;
  • SetLastError 方便后续 Marshal.GetLastWin32Error() 排错。

拓展思考

  1. 64 位迁移陷阱:VB6 代码在 64 位 Windows 仍跑在 WoW64,但 Long 保持 32 位,因此老代码无需改动;若把 VB6 的 Declare 原封不动搬进 VB.NET,则 Long 变 64 位,必须改成 Integer 或 IntPtr,否则参数错位直接崩溃。
  2. 线程与重入:MessageBox 是阻塞调用,会泵送消息,若在 VB6 的 Timer 事件里弹窗可能触发重入,导致栈溢出;面试时可提出用 EnableWindow 或自定义无模式窗体规避。
  3. 替代方案:VB.NET 优先用 MessageBox.Show(封装了 Win32 并支持 IWin32Window 所有者窗体),只有需要获取 LastWin32Error 或自定义 MB_TOPMOST 等扩展标志时才回到 Declare。
  4. 安全编码:对外发布时,不要把用户字符串直接拼进 lpText,应先做长度与格式校验,防止插入 %s、%d 等导致 C 运行时格式化崩溃(虽然 MessageBoxA/W 本身不解释 printf,但养成安全习惯可通过面试官的“安全红线”追问)。