Search

2017/07/09

Powershellでダイアログのボタンとかコントロールを配置:IDEのコードを転用する

Powershellを使えばWidowsフォームも使える。
でも、手打ちでコントロールとか全部やるのは面倒。
そこで、IDEで作成したコードを転用できないかやってみた。
やればできた。

IDEはSharpDevelopで。
新規ソリューションでWindowsアプリケーションを作成
新規ソリューション > C# > Windowsアプリケーション > Windowsアプリケーション

そこからてきとうなコントールを配置。
コードはこんな感じ。



このコードをいい感じに置換してPowershellで表示させる。
というか、EventってPowershellで使えたっけ。

やることはこれ!
■ポリシーの対応
Set-ExecutionPolicy RemoteSigned -Scope Process
■.NETのWindows.Formsの呼び出し
Add-Type -AssemblyName System.Windows.Forms

■newの置換: new -> New-Objet
■thisの置換: this.xxx -> $xxx
■.NETクラスの利用: System.xxx.yyy -> [System.xxx]::yyy
■trueの置換: true -> $true
■falseの置換: false -> $false

■formの表示:$form.showdialog()で。
■Eventの追加:Add Eventで書く


コード的には下記。
Powershellで実行するとこんな感じ。
それっぽくできた。


Set-ExecutionPolicy RemoteSigned -Scope Process #ポリシーの対応として
Add-Type -AssemblyName System.Windows.Forms #.NETのWindows.Formsの呼び出し


           $form = New-Object System.Windows.Forms.Form
$form.AutoScaleDimensions = New-Object System.Drawing.SizeF(8, 15);
$form.AutoScaleMode = [System.Windows.Forms.AutoScaleMode]::Font;
$form.ClientSize = New-Object System.Drawing.Size(282, 253);


            $button1 = new-object System.Windows.Forms.Button;
            $label1  = New-Object System.Windows.Forms.Label;
            $checkBox1= New-Object System.Windows.Forms.CheckBox;


$button1.Location = new-object System.Drawing.Point(179, 165);
$button1.Name = "button1";
$button1.Size = new-object System.Drawing.Size(75, 23);
$button1.TabIndex = 0;
$button1.Text = "ボタン1";
$button1.UseVisualStyleBackColor = $true;



$label1.Location = new-object System.Drawing.Point(138, 50);
$label1.Name = "label1";
$label1.Size = new-object System.Drawing.Size(100, 23);
$label1.TabIndex = 1;
$label1.Text = "ラベル1";

$checkBox1.Location = New-Object System.Drawing.Point(33, 105);
$checkBox1.Name = "checkBox1";
$checkBox1.Size = New-Object System.Drawing.Size(104, 24);
$checkBox1.TabIndex = 2;
$checkBox1.Text = "チェック1";
$checkBox1.UseVisualStyleBackColor = $true;



$form.Name = "MainForm";
$form.Text = "testrrr";
$form.ResumeLayout($false);



$form.Controls.Add($button1);
$form.Controls.Add($label1);
$form.Controls.Add($checkBox1);



    #Add Button event
    $button1.Add_Click(
        {  
[System.Windows.Forms.MessageBox]::Show("Hello World." , "My Dialog Box")
        }
    )


$form.ShowDialog();


これをベースにしていろいろとできるかも。
と言ってもPowershell使うならこんなにGUIの頼らなくていいと思う。


「参考サイト」

TAKE  様
PowerShellでユーザーフォームを作る - サブフォーム編 -
https://letspowershell.blogspot.jp/2016/03/powershell_22.html


コントロールのイベントの書き方はこちら
Wiki  >  TechNet Articles  >  How to Add a PowerShell GUI Event Handler (Part 1)
https://social.technet.microsoft.com/wiki/contents/articles/25911.how-to-add-a-powershell-gui-event-handler-part-1.aspx


Powershellの「Add-type」を詳しく
https://msdn.microsoft.com/en-us/powershell/reference/5.1/microsoft.powershell.utility/add-type

Daisuke Mutaguchi 様のすごく便利に学べる基礎文法です。
PowerShell基礎文法最速マスター
http://winscript.jp/powershell/202

[]

0 件のコメント:

コメントを投稿