Home > OS >  Alias for function from DllImport
Alias for function from DllImport

Time:05-04

[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

CodePudding user response:

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);
}
  • Related