You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

MAUI应用中AppWindow.Title显示Unicode字符为问号问题排查

MAUI窗口标题Unicode字符显示为问号的排查与解决

可能的原因

  • 编码页冲突:复杂应用中的Windows原生API调用可能修改了进程默认代码页,OnWindowCreated事件触发时,MAUI的标题设置逻辑依赖默认代码页的ANSI接口,导致Unicode字符无法正确解析。
  • 窗口初始化时机差异:复杂应用中OnWindowCreated触发时,底层Win32窗口尚未完成Unicode兼容初始化,MAUI封装的标题设置逻辑可能调用了ANSI版本的SetWindowTextA而非Unicode版本的SetWindowTextW,造成字符丢失。
  • 全局配置/第三方依赖干扰:复杂应用引入的Windows特定依赖(如原生库、窗口钩子)可能在OnWindowCreated前后修改了窗口属性或进程编码环境,间接引发标题显示异常。

解决办法

  • 强制使用Unicode原生API设置标题:绕过MAUI封装,直接调用Win32的SetWindowTextW接口确保Unicode支持:
    using System.Runtime.InteropServices;
    
    builder.UseMauiApp<App>()
           .ConfigureLifecycleEvents(events =>
           {
               events.AddWindows(win => win
                   .OnWindowCreated((window) =>
                   {
                       [DllImport("user32.dll", CharSet = CharSet.Unicode)]
                       static extern bool SetWindowTextW(IntPtr hWnd, string lpString);
    
                       SetWindowTextW(window.WindowHandle, "Hello こんにちは World Test");
                   }));
           });
    
  • 调整标题设置时机:不在CreateWindow中设置标题,转而在OnWindowCreated事件内设置,确保窗口初始化完成:
    protected override Window CreateWindow(IActivationState activationState)
    {
        Window window = base.CreateWindow(activationState);
        return window;
    }
    
    // 在ConfigureLifecycleEvents中
    builder.UseMauiApp<App>()
           .ConfigureLifecycleEvents(events =>
           {
               events.AddWindows(win => win
                   .OnWindowCreated((window) =>
                   {
                       window.Title = "Hello こんにちは World Test";
                   }));
           });
    
  • 重置进程编码环境:在应用启动时强制设置Unicode编码,避免默认代码页干扰:
    using System.Globalization;
    using System.Text;
    
    // Program.cs开头添加
    Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
    Encoding.Default = Encoding.UTF8;
    CultureInfo.DefaultThreadCurrentCulture = CultureInfo.InvariantCulture;
    CultureInfo.DefaultThreadCurrentUICulture = CultureInfo.InvariantCulture;
    

内容的提问来源于stack exchange,提问作者mlg

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 14:05:47