如何使用 PowerShell 在 Win32 中使用 SetWindowTextW?

问题描述 投票:0回答:1

我正在尝试使用 PowerShell 更改窗口标题以显示表情符号。

我可以使用...更改进程(有一个窗口)的窗口标题

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

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

$MyNotepadProcess = start-process notepad -PassThru

[Win32]::SetWindowText($MyNotepadProcess.MainWindowHandle, 'My Title')

但是使用

SetWindowTextW
只会混淆输出...

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

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

$MyNotepadProcess = start-process notepad -PassThru

[Win32]::SetWindowTextW($MyNotepadProcess.MainWindowHandle, 'My Title')

我认为我遇到的一个问题是 SetWindowTextW 只接受宽字符串,但我不知道如何将其作为输入提供。
然后我需要使用 `u{1F600} 中的 UniCode 数字添加表情符号(你也是 :))。
(参见开始使用 Win32 和 C++ - 使用字符串

powershell win32gui
1个回答
0
投票

确保正确调用 WinAPI 函数的 Unicode 版本的最简单方法是:

  • CharSet=CharSet.Unicode
    添加到
    [DllImport]
    属性。

  • 省略函数名称中的

    W
    后缀。

// Note the use of "CharSet=CharSet.Unicode" and 
// the function name *without suffix*
[DllImport("User32.dll", CharSet=CharSet.Unicode)]
public static extern int SetWindowText(IntPtr hWnd, string strTitle);

这确保了

SetWindowTextW
,即函数的 Unicode 实现被调用,and .NET 编组 .NET 字符串本质上与原生
LPCWSTR
字符串一样,即作为空终止字符串Unicode 代码单元数组。

© www.soinside.com 2019 - 2024. All rights reserved.