本文介绍了在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:\temp\jpb.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()可以正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 17:43