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

如何在PowerShell中使用Win32的Unicode版SetWindowText设置含emoji窗口标题?

PowerShell修改窗口标题显示Emoji的解决方案

问题

调用Win32 API修改窗口标题时遇到以下问题:

  • 使用SetWindowText时,普通文本正常,但Emoji显示乱码
  • 使用SetWindowTextW时,任何内容都显示乱码,需解决宽字符串传递问题,同时支持通过Unicode编号(如u{1F600})添加Emoji

解决方案

核心是在定义Win32 API时指定CharSet.Unicode,确保字符串编码与宽字符API匹配,同时正确生成Unicode Emoji字符。

步骤1:正确定义Win32 API类

Add-Type -TypeDefinition @"
using System;
using System.Runtime.InteropServices;

public static class Win32 {
  [DllImport("User32.dll", EntryPoint="SetWindowTextW", CharSet = CharSet.Unicode)]
  public static extern bool SetWindowTextW(IntPtr hWnd, string strTitle);
}
"@

步骤2:启动进程并设置带Emoji的标题

# 启动记事本进程
$notepadProc = Start-Process notepad -PassThru
# 短暂等待窗口初始化,避免MainWindowHandle为空
Start-Sleep -Milliseconds 500

# 方式1:直接使用Emoji文本
[Win32]::SetWindowTextW($notepadProc.MainWindowHandle, "我的记事本 😀")

# 方式2:通过Unicode编号生成Emoji
$smileEmoji = [char]::ConvertFromUtf32(0x1F600)
[Win32]::SetWindowTextW($notepadProc.MainWindowHandle, "我的记事本 $smileEmoji")

原理说明

  • SetWindowTextW是Windows宽字符版本的窗口标题设置API,要求传入UTF-16编码字符串。在DllImport中指定CharSet = CharSet.Unicode后,CLR会自动将.NET原生UTF-16字符串转换为API所需的宽字符格式,解决编码不匹配导致的乱码问题。
  • 对于Unicode码点形式的Emoji,使用[char]::ConvertFromUtf32()方法将十六进制码点(如0x1F600)转换为对应字符,即可正常嵌入标题字符串。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 10:37:25