Powershell unable to find type [System.Windows.Forms.KeyEventHandler]

江枫思渺然 提交于 2019-12-22 01:52:33

问题


This might be a pretty simple question but I'm totally lost and searching for an answer hasn't been helpful.

I've got some powershell code to display a simple GUI with TextBoxes. Some of the textboxes allows the user to press Enter to run Button_Click code. When I try running the PS1 script, I get errors saying the following:

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

The strange part, if I close the GUI then re-run the script, I don't get the Unable to find type error and pressing Enter works as desired.

Thinking I had an answer, I tried using [void][reflection.assembly]::Load('System.Windows.Forms.KeyEventHandler') which give this error Exception calling "Load" with "1" argument(s): "Could not load file or assembly 'System.Windows.Forms.KeyEventHandler' or one of its dependencies. [FileNotFoundException]


回答1:


Make sure you load the following assemblies at the top of your script:

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

If it's still not working, you could do something like:

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


来源:https://stackoverflow.com/questions/27791783/powershell-unable-to-find-type-system-windows-forms-keyeventhandler

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!