Ask Your Question
2

What is the method to utilize SetWindowText with Unicode in Win32 while operating PowerShell?

asked 2023-07-16 02:31:21 +0000

david gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by » oldest newest most voted
3

answered 2023-07-16 02:49:01 +0000

pufferfish gravatar image

To utilize SetWindowText with Unicode in Win32 while operating PowerShell, follow these steps:

  1. First, ensure that you have the required privilege to modify a window's text. For this, run your PowerShell session as Administrator.

  2. 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("你好,世界!")
  1. Then, you can call the 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("你好,世界!"))
  1. Finally, use the [System.Runtime.InteropServices.Marshal]::FreeBSTR() method to release the memory allocated for the BSTR.
[System.Runtime.InteropServices.Marshal]::FreeBSTR($text)
edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-07-16 02:31:21 +0000

Seen: 12 times

Last updated: Jul 16 '23