Search code examples
c#powershelldllimport

Alias for function from DllImport


[Win32]::ShowWindowAsync<<..>> works, but this doesn't

Add-Type -TypeDefinition @'
using System;       // IntPtr
using System.Runtime.InteropServices;       // DllImport

public class Win32 {
    [DllImport("user32.dll")] public static extern bool ShowWindowAsync(IntPtr a, int b);
    
    public static bool f_1(IntPtr a, int b) {
        return (ShowWindowAsync(IntPtr a, int b));
    }
}
'@

write-host ([Win32]::f_1((Get-Process -Id $pid).MainWindowHandle, 2))

read-host 'end'

12345678901234567890123456789012345678901234567890123456789012345678901234567890


Solution

  • There are multiple problems with the C# code you pass off to Add-Type. Change the definition of the f_1 method body so that it invokes the extern method correctly (remove the type declarations in front of the arguments you're passing) and make sure you return the return value from it to the caller:

    public static bool f_1(IntPtr a, int b) {
        return ShowWindowAsync(a, b);
    }