使用Windows PowerShell建立WinForm程式

來源:互聯網
上載者:User

Windows PowerShell最突出之處便在於.NET類庫的支援,很大的擴充了指令碼的 能力。這使我們能直接在指令碼中通過System.Windows.Forms程式集來建立視窗。

今天初次嘗試了一下在PowerShell下建立WinForm程式,將完成的這個簡單的 例子分享給大家。

如同在C#編寫WinForm程式中一樣,先建立一個Form類的執行個體,然後初始化: 添加流式布局面板,在面板上加了一個文字框和一個按鈕,給控制項添加必要的事 件處理。當然使用C#的時候通常是VS自動為我們產生一個表單類,並添加了一些 成員和初始化工作的代碼。不過ps貌似還沒有支援WinForm的IDE。

在Form對象建立完畢之後我們就可以把它顯示出來了。先使用Application類 啟用視覺效果,再用Application.Run(Form)方法顯示視窗,啟動訊息迴圈。

Application.Run()可以為我們正確處理視窗的訊息迴圈,在Run()方法外自行 Show視窗會讓視窗一閃而過。

因為代碼比較簡單,熟悉c# WinForm編程的同學應該能一目瞭然,所以不再做 詳細說明。

需要注意的是ps使用反射動態載入程式集的方法和ps中事件的處理方式。

[Reflection.Assembly]::LoadWithPartialName ("System.Windows.Forms")

$app=[System.Windows.Forms.Application]

$myForm=new-object System.Windows.Forms.Form
$myForm.Text="my window"

$button1 = new-object System.Windows.Forms.Button
$button1.Size = new-object System.Drawing.Size  -argumentlist 75, 23
$button1.Text = "點我試試"

$textbox1=new-object System.Windows.Forms.TextBox
$textBox1.Multiline = $true;
$textBox1.Text = "hello world"
$textBox1.Size = new-object System.Drawing.Size  -argumentlist 281, 227

$flowLayoutPanel1 = new-object System.Windows.Forms.FlowLayoutPanel
$myForm.Controls.Add($flowLayoutPanel1)
$flowLayoutPanel1.Controls.Add($textBox1);
$flowLayoutPanel1.Controls.Add($button1);
$flowLayoutPanel1.Dock = "Fill"
$flowLayoutPanel1.FlowDirection = "TopDown"

$button1ClickEventHandler = [System.EventHandler] {
    [System.Windows.Forms.MessageBox]::Show("Hello world! ")
}
$button1.Add_Click($button1ClickEventHandler)

$app::EnableVisualStyles()
$app::Run($myForm)

執行效果如下圖:

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.