2015-01-06 44 views
2

這可能是一個非常簡單的問題,但我完全失去了,尋找答案沒有幫助。Powershell無法找到類型[System.Windows.Forms.KeyEventHandler]

我有一些PowerShell代碼來顯示一個簡單的圖形用戶界面與文本框。一些文本框允許用戶按Enter鍵來運行Button_Click代碼。當我嘗試運行PS1劇本,我得說了以下錯誤:

Unable to find type [System.Windows.Forms.KeyEventHandler]. 
Make sure that the assembly that contains this type is loaded.At C:\Scripts\GUI-Testing.ps1:161 char:1 

$TestVar=[System.Windows.Forms.KeyEventHandler] 
CategoryInfo   : InvalidOperation: (System.Windows.Forms.KeyEventHandler:TypeName) 
FullyQualifiedErrorId : TypeNotFound 

奇怪的一部分,如果我關閉GUI然後重新運行該腳本,我沒有得到Unable to find type錯誤並按下Enter作品如預期的。

思考我有一個答案,我嘗試使用[void][reflection.assembly]::Load('System.Windows.Forms.KeyEventHandler')這給這個錯誤Exception calling "Load" with "1" argument(s): "Could not load file or assembly 'System.Windows.Forms.KeyEventHandler' or one of its dependencies. [FileNotFoundException]

+0

我應該用'[void] [reflection.assembly] :: Load('System.Windows.Forms,Version = 2.0.0.0,文化=中立')' – user4317867

回答

4

確保你在你的腳本的頂部加載以下組件:

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

如果仍然沒有工作,你可以這樣做:

$objForm.KeyPreview = $True 
$objForm.Add_KeyDown({ 
    if ($_.KeyCode -eq "Enter") 
    {  
     #Write Code Here 
    } 
}) 
+0

謝謝,我正在關閉其他例子,並且組件正在按Enter鍵按下變量。有意義powershell會抱怨的事情。現在PowerShell很高興!謝謝! – user4317867