1 | initial version |
To utilize SetWindowText with Unicode in Win32 while operating PowerShell, follow these steps:
First, ensure that you have the required privilege to modify a window's text. For this, run your PowerShell session as Administrator.
Next, use the [System.Runtime.InteropServices.Marshal]::StringToBSTR()
method to convert a .NET Unicode string to a BSTR, which is the native string format used in Windows API functions.
$text = [System.Runtime.InteropServices.Marshal]::StringToBSTR("你好,世界!")
SetWindowTextW()
function from user32.dll using P/Invoke to set the text of a target window. For example, to set the text of a PowerShell console window, you can use the FindWindow()
function to get its handle.Add-Type -Namespace Win32 -Name NativeMethods -MemberDefinition @"
[DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
public static extern bool SetWindowTextW(IntPtr hWnd, [MarshalAs(UnmanagedType.LPWStr)] string lpString);
[DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
public static extern int GetWindowTextW(IntPtr hWnd, [MarshalAs(UnmanagedType.LPWStr)] System.Text.StringBuilder lpString, int nMaxCount);
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
"@
$consoleHwnd = [Win32.NativeMethods]::FindWindow("ConsoleWindowClass", $null)
[Win32.NativeMethods]::SetWindowTextW($consoleHwnd, [System.Runtime.InteropServices.Marshal]::StringToBSTR("你好,世界!"))
[System.Runtime.InteropServices.Marshal]::FreeBSTR()
method to release the memory allocated for the BSTR.[System.Runtime.InteropServices.Marshal]::FreeBSTR($text)