Archive for 4月 22nd, 2012

  1. Hello, Win32 API(PowerShell) World!

    Posted on 4月 22nd, 2012 by cx20

    Win32 API(PowerShell)

    Win32 API は、Windows の機能にアクセスする為の API(Application Programming Interface)である。
    以下は PowerShell での P/Invoke による呼出し例である。


    function Main
       MessageBox 0 "Hello, Win32 API(PowerShell)!" "Hello, World!" 0
    ## Invoke a Win32 P/Invoke call. 
    function Invoke-Win32([string] $dllName, [Type] $returnType, [string] $methodName,  
       [Type[]] $parameterTypes, [Object[]] $parameters) 
       ## Begin to build the dynamic assembly 
       $domain = [AppDomain]::CurrentDomain 
       $name = New-Object Reflection.AssemblyName 'PInvokeAssembly' 
       $assembly = $domain.DefineDynamicAssembly($name, 'Run') 
       $module = $assembly.DefineDynamicModule('PInvokeModule') 
       $type = $module.DefineType('PInvokeType', "Public,BeforeFieldInit") 
       ## Define the actual P/Invoke method
       $method = $type.DefineMethod($methodName, 'Public,HideBySig,Static,PinvokeImpl',  
          $returnType, $parameterTypes) 
       ## Apply the P/Invoke constructor 
       $ctor = [Runtime.InteropServices.DllImportAttribute].GetConstructor([string]) 
       $attr = New-Object Reflection.Emit.CustomAttributeBuilder $ctor, $dllName 
       ## Create the temporary type, and invoke the method. 
       $realType = $type.CreateType() 
       $realType.InvokeMember($methodName, 'Public,Static,InvokeMethod', $null, $null,  
    function MessageBox([Int32] $hWnd, [String] $lpText, [String] $lpCaption, [Int32] $uType) 
       $parameterTypes = [Int32], [String], [String], [Int32]
       $parameters = $hWnd, $lpText, $lpCaption, $uType
       Invoke-Win32 "user32.dll" ([Int32]) "MessageBoxA" $parameterTypes $parameters
    . Main


    C:¥> PowerShell -file hello.ps1


    Hello, World!
    Hello, Win32 API(PowerShell) World!