全5件 (5件中 1-5件目)
1
要は、いちいちpowershellを呼び出すんじゃなくて、一回起動した後何らかのプロセス間通信でUWSCとやり取りすればいい。で、UWSCってウインドウの中身とか受け取るのが得意。そういうわけで、目に見えないWindows.Forms.Formをこさえてやりとりしたらいいんじゃないかな。掲示板の依頼でつくったやつ。アイコンをクリックORキーボードでフォーカスするとアイコンのパスを表示するスクリプト。いちいちバージョン 遅い sendstr(0,"")while !getkeystate( vk_q ) fukidasi( getIconPath() ) sleep( 0.1 )wendexitexitfunction getIconPath() id =getid( GET_ACTIVE_WIN ) if status( id, st_class ) <> "Progman" and status( id, st_class ) <> "cabinetWClass" result ="" exit endif kbd( VK_ctrl, down ) kbd( VK_c, click ) kbd( VK_ctrl, up ) result =getClipPath()fendfunction getClipPath() result =powershell_STA( getClipPath.src ) module getClipPathtextblock src[void][reflection.assembly]::loadwithpartialname("System.Windows.Forms")if ( [windows.forms.clipboard]::ContainsFileDropList() ){ [windows.forms.clipboard]::getFileDropList()}endtextblock endmodulefendfunction powershell_STA( src ) encodedSource =powershell( "[Convert]::ToBase64String([System.Text.Encoding]::Unicode.GetBytes( '" + src + "' ))" ) encodedSource =replace( encodedSource, "<#CR>", "" ) result =powershell( "powershell -sta -EncodedCommand " + encodedSource )fendNo.5143 2018/02/19(Mon) 08:40:56速いバージョン 1回powershellを起動するだけ。 にしても、Windows.Formsの扱いは面倒。RunSpacePoolとかで起動してやらないと、リアルタイムに書き込みできない。sendstr(0,"")thread getClipPath()while !getkeystate( vk_q ) fukidasi( getIconPath() ) sleep( 0.1 )wendexitexitfunction getIconPath() id =getid( GET_ACTIVE_WIN ) if status( id, st_class ) <> "Progman" and status( id, st_class ) <> "cabinetWClass" result ="" exit endif kbd( VK_ctrl, down ) kbd( VK_c, click ) kbd( VK_ctrl, up ) id0 =getid( "getClipPath_hiddenDialog" ) if status( id0, st_isid ) result=getstr( id0, -1, STR_STATIC ) else result="" endiffendprocedure getClipPath() uwsc_pid =status( getid( GET_THISUWSC_WIN ), ST_PROCESS ) src =replace( getClipPath.src, "<PID>", uwsc_pid ) powershell_STA( src ) module getClipPathtextblock src[void][reflection.assembly]::loadwithpartialname("System.Windows.Forms")$UWSC_pid="<PID>"$form=new-object system.windows.forms.form$form.text="getClipPath_hiddenDialog"$form.formborderstyle="none"$form.opacity=0.01$label=new-object system.windows.forms.label$label.parent=$form$rs = [Management.Automation.Runspaces.RunspaceFactory]::CreateRunspace()$rs.Open()$rs.SessionStateProxy.SetVariable("form",$form)$p = $rs.CreatePipeline( { [void] $form.ShowDialog() } )$p.Input.Close()$p.InvokeAsync()do{ if ( [windows.forms.clipboard]::ContainsFileDropList() ){ $pathstr =[windows.forms.clipboard]::getFileDropList() $label.text=$pathstr } else { $label.text="" } if ( !( gwmi win32_process|?{$_.processID -eq $UWSC_pid } ) ) { break }} while ( $true )endtextblock endmodulefendprocedure powershell_STA( src ) encodedSource =powershell( "[Convert]::ToBase64String([System.Text.Encoding]::Unicode.GetBytes( '" + src + "' ))" ) encodedSource =replace( encodedSource, "<#CR>", "" ) powershell( "powershell -sta -EncodedCommand " + encodedSource, true )fend
2018.02.20
コメント(0)
Web電卓それだけhttps://codepen.io/anon/pen/YeYjLO<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <title>電卓</title> </head> <body onload="setCalc()"> <div id="outputArea"> <input type="text" id="outputText"/> </div> <div id="calcKeys" style="display:none">AC,CE,±,√,MC7,8,9,÷,RM4,5,6,×,M+1,2,3,−,SM0,・,=,+,+ </div> <div id="calculator"> <tt> <table/> </tt> </div> <script type="text/javascript">(function(){ var protoKey =document.createElement('button') var protoTR =document.createElement('tr') var protoTD =document.createElement('td') var X,Y; var memory =0; var renew =true; var operation =''; var buttonSize=50; function setCalc(){ var table =document.getElementById('calculator').firstElementChild; var calcKeys =document.getElementById('calcKeys').innerText; var rows=calcKeys.split('\n'); for ( var i=1, rlen=rows.length-1; i < rlen; i++){ var tr =protoTR.cloneNode(); table.appendChild( tr ); var keyData=rows[ i ].split( ',' ); for ( var j = 0, dlen =keyData.length; j < dlen; j++){ var keyDatum =keyData[ j ]; if ( j && (keyDatum == keyData[ j - 1 ] ) ){ var colspan =tr.lastElementChild.getAttribute( 'colspan' ); if ( colspan == null ){ colspan = 2 }else{ colspan++ } var td=tr.lastElementChild; td.setAttribute( 'colspan', colspan ); var btn =td.firstElementChild; var margin =btn.style.margin.replace( /px/, '' ) - 0; btn.style.width=( colspan * buttonSize + ( colspan - 1 ) * margin * 2 ) + 'px'; }else{ setKey( tr, keyDatum ); } } table.appendChild( document.createElement('br') ); } } function setKey( parent, chr ){ var td=protoTD.cloneNode(); var keyButton=protoKey.cloneNode(); keyButton.appendChild( document.createTextNode( chr ) ); keyButton.addEventListener( 'click', doKeyCommand ); keyButton.setAttribute( 'class', 'calcKey' ); keyButton.style.width =buttonSize + 'px' keyButton.style.height =buttonSize + 'px' keyButton.style.margin ='1px'; parent.appendChild( td ) td.appendChild( keyButton ) } function doKeyCommand(){ var keyChar=this.innerText; //alert( keyChar ) if ( numKey( keyChar ) ){ return } if ( dotKey( keyChar ) ){ return } if ( acKey( keyChar ) ){ return } if ( ceKey( keyChar ) ){ return } if ( opeKey( keyChar ) ){ return } if ( memKey( keyChar ) ){ return } alert(renew) } function format(a){ return (' '+a).substr(-18); } function ce(){ document.getElementById( 'outputText' ).value=format( 0 ); X =0; renew =false; } function ac(){ ce(); Y =0; mc(); } function mc(){ memory =0; } function numKey( keyChar ){ var pos ='0123456789'.indexOf( keyChar ); if ( pos < 0 ){ return false; } X=( X + '' + pos ) - 0; if ( renew ){ X=pos; renew =false; } document.getElementById( 'outputText' ).value=format( X ); return true; } function dotKey( keyChar ){ if ( keyChar !=='・' ){return false;} if ( X.toString().match( /[.]/ ) ){return true;} X+='.'; return true; } function acKey( keyChar ){ if ( keyChar !=='AC' ){return false;} ac(); return true; } function ceKey( keyChar ){ if ( keyChar !=='CE' ){return false;} ac(); return true; } function opeKey( keyChar ){ switch( keyChar ){ case '+': case '−': case '×': case '÷': case '=': break; case '√': X =Math.sqrt(X); break; default: return false;// } switch( operation ){ case '+': X +=Y;break; case '−': X =Y-X;break; case '×': X *=Y;break; case '÷': X =Y/X;break; } operation =keyChar; document.getElementById( 'outputText' ).value=format( X ); Y=X; renew=true; return true; } function memKey( keyChar ){ switch( keyChar ){ case 'M+': memory +=X; break; case 'MC': mc(); break; case 'RM': X=memory; document.getElementById( 'outputText' ).value=format( X ); break; case 'SM': memory=X; break; case '±': X=0-X; document.getElementById( 'outputText' ).value=format( X ); break; default: return false; } return true; } setCalc(); ac();})();</script> </body></html>
2018.02.18
コメント(0)
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
コメント(0)
powershellでIE操作しようとすると、私の環境では、DOMがまともに取り扱えません。Microsoft.mshtml のアンセンブリがないためらしく、MS officeをインストールする必要があるのだとか。参考そこで対策。ie.ps1#IEオートメーションを扱う際、microsoht.mshtml.dllが適切にインストールされていないシステムでは、#ドキュメントノードやエレメントのメソッドを呼び出す際、いちいちSystem.__ComObjectを介して#間接的にメソッドを呼ばなければならない。書式は複雑で手順も煩雑なため、IE操作のための関数を用意した。# IEの動作関係# openURL WaitIE WaitForElement IeActivate # System.__ComObjectを介するメソッド呼び出し# invokeComMethod # Dom要素取得# querySelectorAll querySelector getElementById # getElementsByName getElementsByTagName getElementsByClassName# Windowオブジェクトのpowershellから$ie.Document.parentWindowが取得できないのでWindow配下の# メソッド呼び出し・プロパティ読み書きを行う関数も用意する。# windowMethod windowProperty# 参考サイト https://qiita.com/voidProc/items/b3037ccb31676b27ceba###################################################################URLを開くfunction openURL( $url, $visible=$false ){ #IEオブジェクトの取得 try{ [Microsoft.VisualBasic.Interaction]::GetObject|out-null } catch { [reflection.assembly]::LoadWithPartialName("'Microsoft.VisualBasic")|out-null } try{ #ieが起動していればそのオブジェクトを取得 $ie =[Microsoft.VisualBasic.Interaction]::GetObject( "","InternetExplorer.Application" ) } catch { #ieオブジェクトを生成 $ie =new-object -com "InternetExplorer.Application" } $ie.Visible=$visible $ie.Navigate( $url ) return $ie}# IEのページ読み込みが完了するまで待機するfunction WaitIE( $ie, $OkSeconds=0.5 ){ # ビジーでない状態が$OkSeconds秒継続したら読み込み終わったと判断する $limit =( get-date ).AddSeconds( $OkSeconds ) do{ if (($ie.Busy) -or ( $ie.ReadyState -ne 4 )){ $limit =( get-date ).AddSeconds( $OkSeconds ) } sleep -m 100 }while( ( get-date ).CompareTo( $limit ) -lt 0 )}# 要素の出現を待つ(要素はCSSセレクタで指定)function WaitForElement( $ie, [string]$selector ){ WaitIE $ie while( $true ){ try{ if ( $e=(querySelector $ie.Document $selector) ){ break } }catch{[void]"err"} [void]"Loop" }}# このままで動くが、動作が不安定function _IeActivate{ #VB.NETのアセンブリを呼んでおく try{ [void][Microsoft.VisualBasic.Interaction] }catch{ Add-Type -AssemblyName "Microsoft.VisualBasic" } ps iexplore|%{ [Microsoft.VisualBasic.Interaction]::AppActivate($_.id) #ウエイトがないとアクティベートされないらしい。 sleep -m 200 }}# IEウインドウをアクティブにする# function IeActivate( $ie ){ windowMethod $ie "focus"}#####################Windowオブジェクト対策#windowオブジェクト配下のメソッド呼び出しfunction windowMethod{ $ie =$args[0] $methodName =$args[1] $others =if ( ($len=$args.length) -gt 2 ){ $args[2..($len-1)] } else { $null } $sc=new-object -com scriptcontrol $sc.language="vbscript" $sc.addobject("ie",$ie) $statement ="ie.document.parentwindow.$methodName(${others})" #"$statement" $sc.executestatement( $statement )}#ウインドウのプロパティの取得と代入 # 取得 windowProperty $ie "location.Href"# 代入 windowProperty $ie "location.Href" "https://www.infoseek.co.jp/"function windowProperty{ $ie =$args[0] $PropertyName =$args[1] $sc =new-object -com scriptcontrol $sc.language ="vbscript" $sc.addobject("ie",$ie) $statement ="ie.document.parentwindow.$PropertyName" #引数に二つ目があれば代入 if ( $val=$args[2] ){ $assignExpression ="$statement = `"$val`"" $sc.executestatement( $assignExpression ) return $val } else { return $sc.eval( $statement ) }}#####################Com上のメソッド呼び出し#function invokeComMethod( $obj, $methodName ){# return [System.__ComObject].InvokeMember( $methodName, [System.Reflection.BindingFlags]::InvokeMethod, $null, $obj, $args )#}#引数が上の呼び方だと、動かないことがある。#動かない例:invokeComMethod $親要素 "appendChild" $子ノード#動かない例:二重の関数 function elementMethod( $elem, $method ){ invokeComMethod $elem $method }function invokeComMethod{ $obj =$args[0] $methodName =$args[1] $others =if ( ($len=$args.length) -gt 2 ){ $args[2..($len-1)] } else { $null } return [System.__ComObject].InvokeMember( $methodName, [System.Reflection.BindingFlags]::InvokeMethod, $null, $obj, $others )}#########################以下Dom操作# CSSセレクタでノードを得る(複数ノード)function querySelectorAll($node, [string]$selector){ #どういうわけかinvokeComMethodで呼ぶとIEが落ちる $nodes = [System.__ComObject].InvokeMember("querySelectorAll", [System.Reflection.BindingFlags]::InvokeMethod, $null, $node, $selector) #$nodes =invokeComMethod $node "querySelectorAll" $selector #どういうわけか配列のままリターンするとIEが落ちる #return $nodes ではダメ $result = New-Object System.Collections.Generic.List[System.__ComObject] for ($i = 0; $i -lt $nodes.Length; $i++) { $result.Add([System.__ComObject].InvokeMember("item", [System.Reflection.BindingFlags]::InvokeMethod, $null, $nodes, $i)) } $result}# CSSセレクタでノードを得るfunction querySelector($node, [string]$selector){ return invokeComMethod $node "querySelector" $selector}function GetElementById( $node, [string]$ID ){ return invokeComMethod $node "getElementById" $ID}#どういうわけかこちらは配列のままでOK。むしろ、queryselectorAllと同様にすると動かない。以下同様function GetElementsByName( $node, [string]$NAME ){ return invokeComMethod $node "getElementsByName" $NAME}function GetElementsByTagName( $node, [string]$TagName ){ return invokeComMethod $node "getElementsByTagName" $TagName}function GetElementsByClassName( $node, [string]$ClassName ){ return invokeComMethod $node "getElementsByClassName" $ClassName}#########################テストプログラムif ( $myInvocation.InvocationName -like "*\ie.ps1" ){ # (1)Googleの検索結果一覧を取得してみる $ie =OpenUrl "https://www.google.co.jp/search?q=test" WaitIE $ie WaitForElement $ie "h3.r a" "LOADED" $links = querySelectorAll $ie.Document "h3.r a" $links | % { $_.innerText } "-----------------------" # (2)別のキーワードで検索してみる $text = querySelector $ie.Document "#lst-ib" $text.Value = "google" $btn = querySelector $ie.Document "#_fZl" $btn.click() WaitIE $ie "-----------------------" $keyword =getElementById $ie.Document "lst-ib" $keyword.Value "-----------------------" #dom操作を試みる $ie =OpenUrl "about:blank" WaitIE $ie $doc=$ie.document $body=getElementsByTagName $doc "body" #HTMLを直接書き込む $body.innerHTML=@"<div><input type="radio" name="rd" value="1">a<input type="radio" name="rd" value="2">b<input type="radio" name="rd" value="3">c</div>"@ #Dom操作でラジオボタンを追加 $radio_div =(getElementsByName $doc "rd")[0].parentNode $radio_d =invokeComMethod $doc "createElement" "input" invokeComMethod $radio_d "setAttribute" "type" "radio"|out-null invokeComMethod $radio_d "setAttribute" "name" "rd"|out-null invokeComMethod $radio_div "appendChild" $radio_d|out-null $radio_txt_d=invokeComMethod $doc "createTextNode" "d" invokeComMethod $radio_div "appendChild" $radio_txt_d|out-null $ie.Visible = $true IeActivate $ie sleep 2 #Dom操作でラジオボタンをチェック $radios =getElementsByName $doc "rd" $radio=$radios[1] invokeComMethod $radio "setAttribute" "checked"|out-null sleep 4 $ie.Visible = $false #Windowを消してアラート表示 windowMethod $ie "alert" "`"aaa`"" #Windowプロパティ取得 windowProperty $ie "location.Href" #Windowプロパティ代入 windowProperty $ie "location.Href" "https://www.infoseek.co.jp/" WaitIE $ie $ie.Visible = $true IeActivate $ie}
2018.02.07
コメント(0)
いつぞや掲示板で話題になっていたGoogle翻訳。遅ればせながら、関数化してみました。対応言語はtextblockに。※2019/05/28更新今、みたらGoogle翻訳の仕様変更で動かなくなっていたので修正GoogleTranslate.uwsif Get_UWSC_Name = "GoogleTranslate.uws" msgbox(GoogleTranslate( "I love UWSC.", "英語", "日本語" ))endiffunction GoogleTranslate( text, lang_from="自動判別", lang_to="日本語" ) hashtbl langs for lang in split( GogleTranslate.langs, "<#CR>" ) langname =token( ":", lang ) langs[ langname ] =lang next baseURL ="http://translate.google.co.jp/?oe=utf-8&gfe_rd=cr&dcr=0&um=1&ie=UTF-8&hl=ja&client=tw-ob#" query =langs[ lang_from ] + "/" + langs[ lang_to ] + "/" IE =createOleObj( "InternetExplorer.Application" ) IE.Visible=false IE.navigate( baseURL + query + encode( text ) ) while IE.busy or ( IE.ReadyState <> 4 ) sleep(0.1) wend// result=IE.document.getElementById( "result_box" ).innerText Googleの仕様変更で修正//ここから for span in getOleItem(IE.document.getElementsByTagName("span")) if span.GetAttribute("class")="tlid-translation translation" //msgbox(span.innerText) jpstr=span.innerText break endif next result=jpstr//ここまで IE.Quit() module GogleTranslate textblock langsアイスランド語:isアイルランド語:gaアゼルバイジャン語:azアフリカーンス語:afアムハラ語:amアラビア語:arアルバニア語:sqアルメニア語:hyイタリア語:itイディッシュ語:yiイボ語:igインドネシア語:idウェールズ語:cyウクライナ語:ukウズベク語:uzウルドゥ語:urエストニア語:etエスペラント語:eoオランダ語:nlカザフ語:kkカタルーニャ語:caガリシア語:glカンナダ語:knギリシャ語:elキルギス語:kyグジャラト語:guクメール語:kmクルド語:kuクロアチア語:hrコーサ語:xhコルシカ語:coサモア語:smジャワ語:jwジョージア(グルジア)語:kaショナ語:snシンド語:sdシンハラ語:siスウェーデン語:svズールー語:zuスコットランド ゲール語:gdスペイン語:esスロバキア語:skスロベニア語:slスワヒリ語:swスンダ語:suセブアノ語:cebセルビア語:srソト語:stソマリ語:soタイ語:thタガログ語:tlタジク語:tgタミル語:taチェコ語:csチェワ語:nyテルグ語:teデンマーク語:daドイツ語:deトルコ語:trネパール語:neノルウェー語:noハイチ語:htハウサ語:haパシュト語:psバスク語:euハワイ語:hawハンガリー語:huパンジャブ語:paヒンディー語:hiフィンランド語:fiフランス語:frフリジア語:fyブルガリア語:bgベトナム語:viヘブライ語:iwベラルーシ語:beペルシャ語:faベンガル語:bnポーランド語:plボスニア語:bsポルトガル語:ptマオリ語:miマケドニア語:mkマラーティー語:mrマラガシ語:mgマラヤーラム語:mlマルタ語:mtマレー語:msミャンマー語:myモンゴル語:mnモン語:hmnヨルバ語:yoラオ語:loラテン語:laラトビア語:lvリトアニア語:ltルーマニア語:roルクセンブルク語:lbロシア語:ru英語:en韓国語:ko中国語(簡体):zh-CN中国語:zh-CN中国語(繁体):zh-TW日本語:ja自動検出:auto自動判別:auto endtextblock endmodulefend
2018.02.01
コメント(0)
全5件 (5件中 1-5件目)
1


