Author Posts

January 1, 2012 at 12:00 am

by graybin at 2013-04-04 04:03:35

I have a script that starts a windows form. Currently, it brings up the PS Shell and then opens the form. Both appear open at the same time. Is there a way to hide the PS Shell session at times and show it at other times? I tried opening the script with the -WindowStyle Hidden parameter, but then it seemed to either not run, or hide the form also.

Thanks

by DonJ at 2013-04-04 08:09:56

No, you can't.

by nohandle at 2013-04-04 09:21:57

Possible with little help from dll calls.
Add-Type -Name Window -Namespace Console -MemberDefinition '
[DllImport("Kernel32.dll")]
public static extern IntPtr GetConsoleWindow();

[DllImport("user32.dll")]
public static extern bool ShowWindow(IntPtr hWnd, Int32 nCmdShow);
'

function Show-Console {
$consolePtr = [Console.Window]::GetConsoleWindow()
#5 show
[Console.Window]::ShowWindow($consolePtr, 5)
}

function Hide-Console {
$consolePtr = [Console.Window]::GetConsoleWindow()
#0 hide
[Console.Window]::ShowWindow($consolePtr, 0)
}

[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
$Form = New-Object System.Windows.Forms.Form

$showButton = New-Object System.Windows.Forms.Button
$showButton.Text = 'ShowConsole'
$showButton.Top = 10
$showButton.Left = 10
$showButton.Width = 100
$showButton.add_Click({Show-Console})
$form.controls.Add($showButton)

$hideButton = New-Object System.Windows.Forms.Button
$hideButton.Text = 'HideConsole'
$hideButton.Top = 60
$hideButton.Left = 10
$hideButton.Width = 100
$hideButton.add_Click({hide-Console})
$form.controls.Add($hideButton)

$Form.ShowDialog()

by DonJ at 2013-04-04 10:36:03

Ah, hacking ;).

by MasterOfTheHat at 2013-04-05 08:29:41

Nice! And if it works without breaking too many rules, who cares if it's a hack?! It gets the job done and keeps the user from griping! 🙂

by TeewsNek at 2013-04-24 22:17:39

Here is the Function I use in all my script that use forms...

#Region Function Hide-PowerShellWindow
Function Hide-PowerShellWindow()
{
< #
.SYNOPSIS
Hides the PowerShell Console Window
.DESCRIPTION
Hides the PowerShell Console Window
.PARAMETER Handle
The Handle of the Window to Hide
.EXAMPLE
[Void]$(Hide-PowerShellWindow)
.INPUTS
.OUTPUTS
.NOTES
Copyright (c) 2013 by Me
.LINK
#>
[CmdletBinding()]
param (
[IntPtr]$Handle=$(Get-Process -id $PID).MainWindowHandle
)
$WindowDisplay = @"
using System;
using System.Runtime.InteropServices;

namespace Window
{
public class Display
{
[DllImport("user32.dll")]
private static extern bool ShowWindowAsync(IntPtr hWnd, int nCmdShow);

public static bool Hide(IntPtr hWnd)
{
return ShowWindowAsync(hWnd, 0);
}
}
}
"@
Try
{
Add-Type -TypeDefinition $WindowDisplay
[Window.Display]::Hide($Handle)
}
Catch
{
}
}
#EndRegion
[Void]$(Hide-PowerShellWindow)