More P/Invoke in PowerShell

In my last post, I gave an example of how to use P/Invoke through PowerShell  to implement functionality not immediately available via the .Net framework.  My example was to get the owner of a process, and Abhishek wisely pointed out that  this is easier through WMI.

So here’s another example.  It’s actually the one I had written originally, but it didn’t give me an opportunity to illustrate [Ref] parameters, or [Out] parameters via P/Invoke.

param([int] $opacity)

$GWL_EXSTYLE = -20
$WS_EX_LAYERED = 0x80000
$LWA_ALPHA = 0x00000002

## Invoke a Win32 P/Invoke call.
function Invoke-Win32([string] $dllName, [Type] $returnType,
   [string] $methodName, [Type[]] $parameterTypes, [Object[]] $parameters)
{
   (... from last post ...)
# https://www.leeholmes.com/blog/GetTheOwnerOfAProcessInPowerShellPInvokeAndRefOutParameters.aspx } function GetWindowLong($hWnd, $style) { $parameterTypes = [IntPtr], [int] $parameters = [IntPtr] $hWnd, [int] $style Invoke-Win32 "user32" ([Int]) "GetWindowLong" $parameterTypes $parameters } function SetWindowLong($hWnd, $style, $value) { $parameterTypes = [IntPtr], [int], [int] $parameters = [IntPtr] $hWnd, [int] $style, [int] $value Invoke-Win32 "user32" ([Int]) "SetWindowLong" $parameterTypes $parameters } function GetForegroundWindow { Invoke-Win32 "user32" ([Int]) "GetForegroundWindow" } function SetLayeredWindowAttributes([byte] $opacity) { $window = GetForegroundWindow $oldStyle = GetWindowLong $window $GWL_EXSTYLE $result = SetWindowLong $window $GWL_EXSTYLE ($oldStyle -bor $WS_EX_LAYERED) if($result -gt 0) { $parameterTypes = [IntPtr], [int], [byte], [int] $parameters = [IntPtr] $window, [int] 0x00FFFFFF, [byte] $opacity, [int] $LWA_ALPHA [void] (Invoke-Win32 "user32" ([Int]) "SetLayeredWindowAttributes" $parameterTypes $parameters) } } if($opacity -gt 100) { throw "Opacity must be between 0 and 100" } "Switch to the window that you want to adjust. The change will happen in 2 seconds." "(Note that console windows are not supported)" sleep 2 SetLayeredWindowAttributes ($opacity * 255 / 100)

P.S.  I’m off to the Mediterranean until the middle of August.  Can you feed the cats while I’m gone?  🙂

Leave a Reply