Accessing API Methods

by Jun 13, 2016

PowerShell can use C# to define new .NET types that access the internal Windows API methods. Here is some code that makes accessible the ShowWindowAsync() API function which you can use to control application windows. It minimizes your PowerShell instance, waits two seconds, and then restores it:

# create a new .NET type
$signature = @"
[DllImport("user32.dll")]public static extern bool ShowWindowAsync(IntPtr hWnd, int nCmdShow);
"@
Add-Type -MemberDefinition $signature -Name MyType -Namespace MyNamespace

# find window handle of current PowerShell instance
$handle = (Get-Process -Id $PID).MainWindowHandle

# Minimize the Windows PowerShell console
$null = [MyNamespace.MyType]::ShowWindowAsync($handle, 2)

Start-Sleep -Seconds 2

# Restore it
$null = [MyNamespace.MyType]::ShowWindowAsync($handle, 4)

A word of caution: accessing low-level API functions requires a good understanding of what you are doing. Websites like pinvoke.net try to catalogize and document many of the Windows API functions.

Twitter This Tip! ReTweet this Tip!