Powershell cannot find type [System.Windows.Forms.KeyEventHandler]

This might be a pretty simple question, but I'm completely lost and looking for an answer didn't help.

I have powershell code to display a simple GUI with TextBoxes. Some text boxes allow the user to press Enter to trigger the Button_Click code. When I try to run 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 weird part is, if I close the GUI and then run the script, I don't get the error Unable to find type

and hitting Enter works as desired.

I think I had the answer, I tried using [void][reflection.assembly]::Load('System.Windows.Forms.KeyEventHandler')

which give this errorException calling "Load" with "1" argument(s): "Could not load file or assembly 'System.Windows.Forms.KeyEventHandler' or one of its dependencies. [FileNotFoundException]

+3


source to share


1 answer


Make sure you download 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 still doesn't work, you can do something like:

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

      

+6


source







All Articles