Powershell无法找到类型[System.Windows.Forms.KeyEventHandler]

use*_*867 14 powershell user-interface .net-assembly

这可能是一个非常简单的问题,但我完全迷失了,寻找答案并没有帮助.

我有一些powershell代码来显示带有TextBoxes的简单GUI.某些文本框允许用户按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
Run Code Online (Sandbox Code Playgroud)

奇怪的一部分,如果我关闭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]

小智 16

确保在脚本顶部加载以下程序集:

[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Drawing") 
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms") 
Run Code Online (Sandbox Code Playgroud)

如果它仍然无法正常工作,您可以执行以下操作:

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

  • 为什么不添加类型-AssemblyName“System.Windows.Forms”? (2认同)
  • `add-type ....` 和 `[System.Reflection.Assembly]::LoadWithPartialName(...)` 都没有任何效果。两者都执行时没有错误,但“Forms”程序集/模块只是没有加载。有任何提示吗? (2认同)