|
カテゴリ:powershell
UWSCだとDEF_DLL命令で簡単に呼べるんだけど、powershellだと結構な手間。
そこで、DLL関数を作ってくれる関数を作ってみました。 呼び出し方はテストプログラムを参考に。 setApiFunc #Win32Apiを呼び出す関数を設定する関数 # setApiFunc 任意の関数名 API関数のスペックを格納するハッシュ #ハッシュの構造はテストプログラムの$funcSpecを参照。型名はC#の記法による。 # #Win32Apiの一覧はhttps://msdn.microsoft.com/ja-jp/windows/hh240557#10 # function setApiFunc( $funcName, $funcSpec ){ $csProto = @" [DllImport(`"<DllName>`")] public static extern <retType> <DllFunc>( <argSpec> ); "@ if ( !$funcName ){return $false} if ( !( $DllName=$funcSpec.DllName ) ){return $false} if ( !( $DllFunc=$funcSpec.DllFunc ) ){return $false} if ( !( $retType=$funcSpec.retType ) ){return $false} #if ( !$funcSpec.argTypes ){return $false} $decl=@() $argN=0 $dmyVars=@() if ( $funcSpec.argTypes ){ $funcSpec.argTypes -split ","|%{ $dmyVar ="dmy" + $argN++ $dmyVars+=,"`$$dmyVar" $decl +=,"$_ ${dmyVar}," } } $argSpec =$decl -join "" -replace ",$","" $csc =$csProto -replace "<DllName>", $DllName -replace "<DllFunc>", $DllFunc $csc =$csc -replace "<retType>", $retType -replace "<argSpec>", $argSpec $csc ="@`"`n${csc}`n`"@" # $apiCode ="add-type -memberDefinition $csc -name 'Win32ApiFunctions' -passthru" $apiCode ="add-type -memberDefinition $csc -name (`"api_`"+(get-date).ticks) -passthru" $argstr =$dmyVars -join "," $code="new-item -force -path function:global:$funcName -value { param ( $argstr );($apiCode)::$DllFunc( $argstr )}|out-null" iex $code #(gi function:$funcName).definition } ######################################################################### # テストプログラム win32のMessageBoxを呼ぶmsgbox関数を作成する例 if ( $myInvocation.InvocationName -like "*setApiFunc.ps1" ){ $funcSpec=@{ DllFunc="MessageBox"; DllName="user32.dll"; retType="int"; argTypes="IntPtr,string,string,UInt32" } setApiFunc "msgbox" $funcSpec $funcSpec=@{ DllFunc="FindWindow"; DllName="user32.dll"; retType="IntPtr"; argTypes="string,string" } setApiFunc "GetWindowHandle" $funcSpec $funcSpec=@{ DllFunc="SetWindowText"; DllName="user32.dll"; retType="void"; argTypes="IntPtr,string" } setApiFunc "reWriteWindowTitle" $funcSpec msgbox 0 "Hello World!" "Test" 3 notepad sleep 3 reWriteWindowTitle ( GetWindowHandle "Notepad" "無題 - メモ帳" ) "タイトルを書き換えました" $spec=@{} $spec.DllFunc="LockWorkStation" $spec.DllName="user32.dll" $spec.retType="void" setApiFunc lock $spec sleep -m 500 lock } お気に入りの記事を「いいね!」で応援しよう
最終更新日
2018.02.16 15:04:32
コメント(0) | コメントを書く
[powershell] カテゴリの最新記事
|