11/15/10

PInvoke SetWindowText PowerShell Script

P/Invoke examples for the SetWindowText Windows API Function.
These examples set the window text/title for Notepad.exe.
#get notepad window handle
$notepad = get-process notepad
$notepad.mainWindowHandle //100000, intptr structure

$pinvoke::setWindowText($notepad.mainWindowHandle, "a")

#auto-convert int to intptr
$pinvoke::setWindowText(100000, "b")

#create intptr
#out-null to suppress bool result
$pinvoke::setWindowText((new-object intPtr(100000)), "c") | out-null

$pinvoke::setWindowTextCustomWrapper(100000)

Implementation #1 simply exposes the SetWindowText method, the member definition uses C# syntax.
$pinvoke = add-type -name pinvoke -passThru -memberDefinition @'

[DllImport("user32.dll", CharSet = CharSet.Auto)]
public static extern bool SetWindowText(IntPtr hwnd, String lpString);

'@

Implementation #2, same as #1 but written on one line.
$pinvoke = add-type -name pinvoke -passThru -memberDefinition '[DllImport("user32.dll", CharSet = CharSet.Auto)]public static extern bool SetWindowText(IntPtr hwnd, String lpString);'

Implementation #3, SetWindowText is private, add custom wrapper method.
$pinvoke = add-type -name pinvoke -passThru -memberDefinition @'

[DllImport("user32.dll", CharSet = CharSet.Auto)]
private static extern bool SetWindowText(IntPtr hwnd, String lpString);

public static void SetWindowTextCustomWrapper(IntPtr handle)
{
string customText = string.Format("handle: {0}", handle);
SetWindowText(handle, customText);
}

'@


No comments:

Post a Comment