Evi*_*cat 6 forms windows console powershell user-interface
我试图将我的powershell控制台放在前面,即使它被最小化.我找到了以下代码:
function Show-Process($Process, [Switch]$Maximize)
{
$sig = '
[DllImport("user32.dll")] public static extern bool ShowWindowAsync(IntPtr hWnd, int nCmdShow);
[DllImport("user32.dll")] public static extern int SetForegroundWindow(IntPtr hwnd);
'
if ($Maximize) { $Mode = 3 } else { $Mode = 4 }
$type = Add-Type -MemberDefinition $sig -Name WindowAPI -PassThru
$hwnd = $process.MainWindowHandle
$null = $type::ShowWindowAsync($hwnd, $Mode)
$null = $type::SetForegroundWindow($hwnd)
}
Show-Process -Process (Get-Process -Id $pid)
Run Code Online (Sandbox Code Playgroud)
它工作正常,但当我从Button Click事件调用该函数时,控制台不会显示.问题是什么?有没有办法在使用WinForms GUI时将powershell控制台置于前面?
以下是示例GUI代码:
function Show-Process($Process, [Switch]$Maximize)
{
$sig = '
[DllImport("user32.dll")] public static extern bool ShowWindowAsync(IntPtr hWnd, int nCmdShow);
[DllImport("user32.dll")] public static extern int SetForegroundWindow(IntPtr hwnd);
'
if ($Maximize) { $Mode = 3 } else { $Mode = 4 }
$type = Add-Type -MemberDefinition $sig -Name WindowAPI -PassThru
$hwnd = $process.MainWindowHandle
$null = $type::ShowWindowAsync($hwnd, $Mode)
$null = $type::SetForegroundWindow($hwnd)
}
Add-Type -AssemblyName System.Windows.Forms
[System.Windows.Forms.Application]::EnableVisualStyles()
$Form = New-Object system.Windows.Forms.Form
$Form.ClientSize = '446,266'
$Form.text = "Form"
$Form.TopMost = $false
$Button1 = New-Object system.Windows.Forms.Button
$Button1.text = "button"
$Button1.width = 60
$Button1.height = 30
$Button1.location = New-Object System.Drawing.Point(75,29)
$Button1.Font = 'Microsoft Sans Serif,10'
$Button1.Add_Click({
Show-Process -Process (Get-Process -Id $pid)
})
$Form.controls.AddRange(@($Button1))
[void]$Form.ShowDialog()
Run Code Online (Sandbox Code Playgroud)
不幸的是,我无法完全修复它,但也许其他人可能会根据我的发现进一步帮助您:
首先,按钮单击事件中的进程与父 PowerShell 主机运行的进程空间不同。这可以很容易地证明,但会揭示函数中的$hwhdwith并在调用之前调用该函数:Write-Host $hwndShow-ProcessShow-ProcessShowDialog
Show-Process -Process (Get-Process -Id $pid)
[void]$Form.ShowDialog()
Run Code Online (Sandbox Code Playgroud)
换句话说:要修复此部分,您需要$Pid首先从 PowerShell 窗口捕获父级:
$Button1.Add_Click({
Show-Process -Process $MyProcess
})
$Form.controls.AddRange(@($Button1))
$MyProcess = Get-Process -Id $pid
Show-Process -Process $MyProcess
[void]$Form.ShowDialog()
Run Code Online (Sandbox Code Playgroud)
上面的代码片段有效,但是一旦我删除(或注释掉)该行Show-Process -Process $MyProcess(在主机级别),它就会再次中断......
| 归档时间: |
|
| 查看次数: |
583 次 |
| 最近记录: |