在 PowerShell Form.Show() 中无法正常工作,但 Form.ShowDialog() 可以 [英] In PowerShell Form.Show() does not work right, but Form.ShowDialog() does

查看:14
本文介绍了在 PowerShell Form.Show() 中无法正常工作,但 Form.ShowDialog() 可以的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过 powershell 显示图像.我基于 这个论坛帖子.

I am trying to display an image via powershell. I made a script based on this forum post.

如果我使用 ShowDialog() 它工作正常,除了在对话框启动时 powershell 执行停止.但是,这是为模态对话框设计的.如果我调用 Form.Show() 在 PowershellISE 中,表单会显示,但会冻结且无法移动或关闭.如果我将代码复制并粘贴到 powershell 控制台,行为是相似的.

If I use ShowDialog() it works fine, except the powershell execution stops while the dialog is up. However, that is by design for a modal dialog. If I call Form.Show() in PowershellISE the form shows up, but freezes and cannot be moved or dismissed. Behavior is similar if I copy and past the code to a powershell console.

如何使对话框非模态,而不是冻结.

How do I make the dialog non-modal, and not freeze.

推荐答案

第一个答案为什么会附加.

在 Windows 图形程序中,创建窗口的线程必须在消息泵中循环,以便将来自用户操作的消息重新分配(翻译)到其 Windows 中的事件.

In a Windows graphic program the thread which create a Window must loop in a message pump in order to redistribute (translate) messages coming from the user action to events in his Windows.

在模态窗口中,处理窗口显示的模态代码会运行自己的消息泵循环,并且在窗口关闭之前不会返回.这就是为什么 ShowDialog() 之后的代码在窗口关闭之前不会执行.

In a modal window, the modal code that handles the window display runs its own message pump loop and doesn't return until the window is closed. That's why the code after ShowDialog() won't execute until the window is closed.

Show(),只是要求显示窗口,但如果没有泵循环来管理来自用户操作的消息,它就会冻结.

Show(), just ask to show the Window, but if there is no pump loop to manage the messages coming from user action, it just freezes.

第二个拥有两个线程的简单方法

CmdLet 启动作业使用 Powershell 分配的池中的另一个线程,因此它使对话框非模态,并且不会冻结.

The CmdLet start-job use another thread from the pool allocated by Powershell so it makes the dialog non-modal, and it does not freeze.

function goForm
{
  [void][reflection.assembly]::LoadWithPartialName("System.Windows.Forms")

  $file = (get-item 'C:	empjpb.png')
  #$file = (get-item "c:image.jpg")

  $img = [System.Drawing.Image]::Fromfile($file);

  # This tip from http://stackoverflow.com/questions/3358372/windows-forms-look-different-in-powershell-and-powershell-ise-why/3359274#3359274
  [System.Windows.Forms.Application]::EnableVisualStyles();
  $form = new-object Windows.Forms.Form
  $form.Text = "Image Viewer"
  $form.Width = $img.Size.Width;
  $form.Height =  $img.Size.Height;
  $pictureBox = new-object Windows.Forms.PictureBox
  $pictureBox.Width =  $img.Size.Width;
  $pictureBox.Height =  $img.Size.Height;

  $pictureBox.Image = $img;
  $form.controls.add($pictureBox)
  $form.Add_Shown( { $form.Activate() } )
  $form.ShowDialog()
}

Clear-Host

start-job $function:goForm

$name = Read-Host "What is you name"
Write-Host "your name is $name"

这篇关于在 PowerShell Form.Show() 中无法正常工作,但 Form.ShowDialog() 可以的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆