Skip to content

Instantly share code, notes, and snippets.

Created July 31, 2017 15:05
Show Gist options
  • Save anonymous/b4771d2b5a2e3aa7e6506a3ef188be07 to your computer and use it in GitHub Desktop.
Save anonymous/b4771d2b5a2e3aa7e6506a3ef188be07 to your computer and use it in GitHub Desktop.
if ([Environment]::OSVersion.Version.Major -lt 10)
{
Write-Error "Windows 10 or above is required to run this script"
exit -1
}
Add-Type -Language CSharp -TypeDefinition @'
using System;
using System.Runtime.InteropServices;
using System.ComponentModel;
// Based on http://stackoverflow.com/a/32417530, Windows 10 SDK and github project VirtualDesktop
namespace VirtualDesktop
{
internal static class Guids
{
public static readonly Guid CLSID_ImmersiveShell = new Guid("C2F03A33-21F5-47FA-B4BB-156362A2F239");
public static readonly Guid CLSID_VirtualDesktopManagerInternal = new Guid("C5E0CDCA-7B6E-41B2-9FC4-D93975CC467B");
public static readonly Guid CLSID_VirtualDesktopManager = new Guid("AA509086-5CA9-4C25-8F95-589D3C07B48A");
public static readonly Guid CLSID_VirtualDesktopPinnedApps = new Guid("B5A399E7-1C87-46B8-88E9-FC5747B171BD");
}
[StructLayout(LayoutKind.Sequential)]
internal struct Size
{
public int X;
public int Y;
}
[StructLayout(LayoutKind.Sequential)]
internal struct Rect
{
public int Left;
public int Top;
public int Right;
public int Bottom;
}
internal enum APPLICATION_VIEW_CLOAK_TYPE : int
{
AVCT_NONE = 0,
AVCT_DEFAULT = 1,
AVCT_VIRTUAL_DESKTOP = 2
}
internal enum APPLICATION_VIEW_COMPATIBILITY_POLICY : int
{
AVCP_NONE = 0,
AVCP_SMALL_SCREEN = 1,
AVCP_TABLET_SMALL_SCREEN = 2,
AVCP_VERY_SMALL_SCREEN = 3,
AVCP_HIGH_SCALE_FACTOR = 4
}
[ComImport]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[Guid("9AC0B5C8-1484-4C5B-9533-4134A0F97CEA")]
internal interface IApplicationView
{
int SetFocus();
int SwitchTo();
int TryInvokeBack(IntPtr /* IAsyncCallback* */ callback);
int GetThumbnailWindow(out IntPtr hwnd);
int GetMonitor(out IntPtr /* IImmersiveMonitor */ immersiveMonitor);
int GetVisibility(out int visibility);
int SetCloak(APPLICATION_VIEW_CLOAK_TYPE cloakType, int unknown);
int GetPosition(ref Guid guid /* GUID for IApplicationViewPosition */, out IntPtr /* IApplicationViewPosition** */ position);
int SetPosition(ref IntPtr /* IApplicationViewPosition* */ position);
int InsertAfterWindow(IntPtr hwnd);
int GetExtendedFramePosition(out Rect rect);
int GetAppUserModelId([MarshalAs(UnmanagedType.LPWStr)] out string id);
int SetAppUserModelId(string id);
int IsEqualByAppUserModelId(string id, out int result);
int GetViewState(out uint state);
int SetViewState(uint state);
int GetNeediness(out int neediness);
int GetLastActivationTimestamp(out ulong timestamp);
int SetLastActivationTimestamp(ulong timestamp);
int GetVirtualDesktopId(out Guid guid);
int SetVirtualDesktopId(ref Guid guid);
int GetShowInSwitchers(out int flag);
int SetShowInSwitchers(int flag);
int GetScaleFactor(out int factor);
int CanReceiveInput(out bool canReceiveInput);
int GetCompatibilityPolicyType(out APPLICATION_VIEW_COMPATIBILITY_POLICY flags);
int SetCompatibilityPolicyType(APPLICATION_VIEW_COMPATIBILITY_POLICY flags);
int GetPositionPriority(out IntPtr /* IShellPositionerPriority** */ priority);
int SetPositionPriority(IntPtr /* IShellPositionerPriority* */ priority);
int GetSizeConstraints(IntPtr /* IImmersiveMonitor* */ monitor, out Size size1, out Size size2);
int GetSizeConstraintsForDpi(uint uint1, out Size size1, out Size size2);
int SetSizeConstraintsForDpi(ref uint uint1, ref Size size1, ref Size size2);
int QuerySizeConstraintsFromApp();
int OnMinSizePreferencesUpdated(IntPtr hwnd);
int ApplyOperation(IntPtr /* IApplicationViewOperation* */ operation);
int IsTray(out bool isTray);
int IsInHighZOrderBand(out bool isInHighZOrderBand);
int IsSplashScreenPresented(out bool isSplashScreenPresented);
int Flash();
int GetRootSwitchableOwner(out IApplicationView rootSwitchableOwner);
int EnumerateOwnershipTree(out IObjectArray ownershipTree);
int GetEnterpriseId([MarshalAs(UnmanagedType.LPWStr)] out string enterpriseId);
int IsMirrored(out bool isMirrored);
}
[ComImport]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[Guid("2C08ADF0-A386-4B35-9250-0FE183476FCC")]
internal interface IApplicationViewCollection
{
int GetViews(out IObjectArray array);
int GetViewsByZOrder(out IObjectArray array);
int GetViewsByAppUserModelId(string id, out IObjectArray array);
int GetViewForHwnd(IntPtr hwnd, out IApplicationView view);
int GetViewForApplication(object application, out IApplicationView view);
int GetViewForAppUserModelId(string id, out IApplicationView view);
int GetViewInFocus(out IntPtr view);
void outreshCollection();
int RegisterForApplicationViewChanges(object listener, out int cookie);
int RegisterForApplicationViewPositionChanges(object listener, out int cookie);
int UnregisterForApplicationViewChanges(int cookie);
}
[ComImport]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[Guid("FF72FFDD-BE7E-43FC-9C03-AD81681E88E4")]
internal interface IVirtualDesktop
{
bool IsViewVisible(IApplicationView view);
Guid GetId();
}
[ComImport]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[Guid("F31574D6-B682-4CDC-BD56-1827860ABEC6")]
internal interface IVirtualDesktopManagerInternal
{
int GetCount();
void MoveViewToDesktop(IApplicationView view, IVirtualDesktop desktop);
bool CanViewMoveDesktops(IApplicationView view);
IVirtualDesktop GetCurrentDesktop();
void GetDesktops(out IObjectArray desktops);
[PreserveSig]
int GetAdjacentDesktop(IVirtualDesktop from, int direction, out IVirtualDesktop desktop);
void SwitchDesktop(IVirtualDesktop desktop);
IVirtualDesktop CreateDesktop();
void RemoveDesktop(IVirtualDesktop desktop, IVirtualDesktop fallback);
IVirtualDesktop FindDesktop(ref Guid desktopid);
}
[ComImport]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[Guid("A5CD92FF-29BE-454C-8D04-D82879FB3F1B")]
internal interface IVirtualDesktopManager
{
bool IsWindowOnCurrentVirtualDesktop(IntPtr topLevelWindow);
Guid GetWindowDesktopId(IntPtr topLevelWindow);
void MoveWindowToDesktop(IntPtr topLevelWindow, ref Guid desktopId);
}
[ComImport]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[Guid("4CE81583-1E4C-4632-A621-07A53543148F")]
internal interface IVirtualDesktopPinnedApps
{
bool IsAppIdPinned(string appId);
void PinAppID(string appId);
void UnpinAppID(string appId);
bool IsViewPinned(IApplicationView applicationView);
void PinView(IApplicationView applicationView);
void UnpinView(IApplicationView applicationView);
}
[ComImport]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[Guid("92CA9DCD-5622-4BBA-A805-5E9F541BD8C9")]
internal interface IObjectArray
{
void GetCount(out int count);
void GetAt(int index, ref Guid iid, [MarshalAs(UnmanagedType.Interface)]out object obj);
}
[ComImport]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[Guid("6D5140C1-7436-11CE-8034-00AA006009FA")]
internal interface IServiceProvider10
{
[return: MarshalAs(UnmanagedType.IUnknown)]
object QueryService(ref Guid service, ref Guid riid);
}
internal static class DesktopManager
{
static DesktopManager()
{
var shell = (IServiceProvider10)Activator.CreateInstance(Type.GetTypeFromCLSID(Guids.CLSID_ImmersiveShell));
VirtualDesktopManagerInternal = (IVirtualDesktopManagerInternal)shell.QueryService(Guids.CLSID_VirtualDesktopManagerInternal, typeof(IVirtualDesktopManagerInternal).GUID);
VirtualDesktopManager = (IVirtualDesktopManager)Activator.CreateInstance(Type.GetTypeFromCLSID(Guids.CLSID_VirtualDesktopManager));
ApplicationViewCollection = (IApplicationViewCollection)shell.QueryService(typeof(IApplicationViewCollection).GUID, typeof(IApplicationViewCollection).GUID);
VirtualDesktopPinnedApps = (IVirtualDesktopPinnedApps)shell.QueryService(Guids.CLSID_VirtualDesktopPinnedApps, typeof(IVirtualDesktopPinnedApps).GUID);
}
internal static IVirtualDesktopManagerInternal VirtualDesktopManagerInternal;
internal static IVirtualDesktopManager VirtualDesktopManager;
internal static IApplicationViewCollection ApplicationViewCollection;
internal static IVirtualDesktopPinnedApps VirtualDesktopPinnedApps;
internal static IVirtualDesktop GetDesktop(int index)
{ // get desktop with index
int count = VirtualDesktopManagerInternal.GetCount();
if (index < 0 || index >= count) throw new ArgumentOutOfRangeException("index");
IObjectArray desktops;
VirtualDesktopManagerInternal.GetDesktops(out desktops);
object objdesktop;
desktops.GetAt(index, typeof(IVirtualDesktop).GUID, out objdesktop);
Marshal.ReleaseComObject(desktops);
return (IVirtualDesktop)objdesktop;
}
internal static int GetDesktopIndex(IVirtualDesktop desktop)
{ // get index of desktop
int index = -1;
Guid IdSearch = desktop.GetId();
IObjectArray desktops;
VirtualDesktopManagerInternal.GetDesktops(out desktops);
object objdesktop;
for (int i = 0; i < VirtualDesktopManagerInternal.GetCount(); i++)
{
desktops.GetAt(i, typeof(IVirtualDesktop).GUID, out objdesktop);
if (IdSearch.CompareTo(((IVirtualDesktop)objdesktop).GetId()) == 0)
{ index = i;
break;
}
}
Marshal.ReleaseComObject(desktops);
return index;
}
internal static IApplicationView GetApplicationView(this IntPtr hWnd)
{ // get application view to window handle
IApplicationView view;
ApplicationViewCollection.GetViewForHwnd(hWnd, out view);
return view;
}
internal static string GetAppId(IntPtr hWnd)
{ // get Application ID to window handle
string appId;
hWnd.GetApplicationView().GetAppUserModelId(out appId);
return appId;
}
}
public class Desktop
{
private IVirtualDesktop ivd;
private Desktop(IVirtualDesktop desktop) { this.ivd = desktop; }
public override int GetHashCode()
{ // Get hash
return ivd.GetHashCode();
}
public override bool Equals(object obj)
{ // Compares with object
var desk = obj as Desktop;
return desk != null && object.ReferenceEquals(this.ivd, desk.ivd);
}
public static int Count
{ // Returns the number of desktops
get { return DesktopManager.VirtualDesktopManagerInternal.GetCount(); }
}
public static Desktop Current
{ // Returns current desktop
get { return new Desktop(DesktopManager.VirtualDesktopManagerInternal.GetCurrentDesktop()); }
}
public static Desktop FromIndex(int index)
{ // Create desktop object from index 0..Count-1
return new Desktop(DesktopManager.GetDesktop(index));
}
public static Desktop FromWindow(IntPtr hWnd)
{ // Creates desktop object on which window <hWnd> is displayed
if (hWnd == IntPtr.Zero) throw new ArgumentNullException();
Guid id = DesktopManager.VirtualDesktopManager.GetWindowDesktopId(hWnd);
return new Desktop(DesktopManager.VirtualDesktopManagerInternal.FindDesktop(ref id));
}
public static int FromDesktop(Desktop desktop)
{ // Returns index of desktop object or -1 if not found
return DesktopManager.GetDesktopIndex(desktop.ivd);
}
public static Desktop Create()
{ // Create a new desktop
return new Desktop(DesktopManager.VirtualDesktopManagerInternal.CreateDesktop());
}
public void Remove(Desktop fallback = null)
{ // Destroy desktop and switch to <fallback>
IVirtualDesktop fallbackdesktop;
if (fallback == null)
{ // if no fallback is given use desktop to the left except for desktop 0.
Desktop dtToCheck = new Desktop(DesktopManager.GetDesktop(0));
if (this.Equals(dtToCheck))
{ // desktop 0: set fallback to second desktop (= "right" desktop)
DesktopManager.VirtualDesktopManagerInternal.GetAdjacentDesktop(ivd, 4, out fallbackdesktop); // 4 = RightDirection
}
else
{ // set fallback to "left" desktop
DesktopManager.VirtualDesktopManagerInternal.GetAdjacentDesktop(ivd, 3, out fallbackdesktop); // 3 = LeftDirection
}
}
else
// set fallback desktop
fallbackdesktop = fallback.ivd;
DesktopManager.VirtualDesktopManagerInternal.RemoveDesktop(ivd, fallbackdesktop);
}
public bool IsVisible
{ // Returns <true> if this desktop is the current displayed one
get { return object.ReferenceEquals(ivd, DesktopManager.VirtualDesktopManagerInternal.GetCurrentDesktop()); }
}
public void MakeVisible()
{ // Make this desktop visible
DesktopManager.VirtualDesktopManagerInternal.SwitchDesktop(ivd);
}
public Desktop Left
{ // Returns desktop at the left of this one, null if none
get
{
IVirtualDesktop desktop;
int hr = DesktopManager.VirtualDesktopManagerInternal.GetAdjacentDesktop(ivd, 3, out desktop); // 3 = LeftDirection
if (hr == 0)
return new Desktop(desktop);
else
return null;
}
}
public Desktop Right
{ // Returns desktop at the right of this one, null if none
get
{
IVirtualDesktop desktop;
int hr = DesktopManager.VirtualDesktopManagerInternal.GetAdjacentDesktop(ivd, 4, out desktop); // 4 = RightDirection
if (hr == 0)
return new Desktop(desktop);
else
return null;
}
}
public void MoveWindow(IntPtr hWnd)
{ // Move window <hWnd> to this desktop
if (hWnd == IntPtr.Zero) throw new ArgumentNullException();
if (hWnd == GetConsoleWindow())
{ // own window
try // the easy way (powershell's own console)
{
DesktopManager.VirtualDesktopManager.MoveWindowToDesktop(hWnd, ivd.GetId());
}
catch // powershell in cmd console
{
IApplicationView view;
DesktopManager.ApplicationViewCollection.GetViewForHwnd(hWnd, out view);
DesktopManager.VirtualDesktopManagerInternal.MoveViewToDesktop(view, ivd);
}
}
else
{ // window of other process
IApplicationView view;
DesktopManager.ApplicationViewCollection.GetViewForHwnd(hWnd, out view);
DesktopManager.VirtualDesktopManagerInternal.MoveViewToDesktop(view, ivd);
}
}
public bool HasWindow(IntPtr hWnd)
{ // Returns true if window <hWnd> is on this desktop
if (hWnd == IntPtr.Zero) throw new ArgumentNullException();
return ivd.GetId() == DesktopManager.VirtualDesktopManager.GetWindowDesktopId(hWnd);
}
public static bool IsWindowPinned(IntPtr hWnd)
{ // Returns true if window <hWnd> is pinned to all desktops
if (hWnd == IntPtr.Zero) throw new ArgumentNullException();
return DesktopManager.VirtualDesktopPinnedApps.IsViewPinned(hWnd.GetApplicationView());
}
public static void PinWindow(IntPtr hWnd)
{ // pin window <hWnd> to all desktops
if (hWnd == IntPtr.Zero) throw new ArgumentNullException();
var view = hWnd.GetApplicationView();
if (!DesktopManager.VirtualDesktopPinnedApps.IsViewPinned(view))
{ // pin only if not already pinned
DesktopManager.VirtualDesktopPinnedApps.PinView(view);
}
}
public static void UnpinWindow(IntPtr hWnd)
{ // unpin window <hWnd> from all desktops
if (hWnd == IntPtr.Zero) throw new ArgumentNullException();
var view = hWnd.GetApplicationView();
if (DesktopManager.VirtualDesktopPinnedApps.IsViewPinned(view))
{ // unpin only if not already unpinned
DesktopManager.VirtualDesktopPinnedApps.UnpinView(view);
}
}
public static bool IsApplicationPinned(IntPtr hWnd)
{ // Returns true if application for window <hWnd> is pinned to all desktops
if (hWnd == IntPtr.Zero) throw new ArgumentNullException();
return DesktopManager.VirtualDesktopPinnedApps.IsAppIdPinned(DesktopManager.GetAppId(hWnd));
}
public static void PinApplication(IntPtr hWnd)
{ // pin application for window <hWnd> to all desktops
if (hWnd == IntPtr.Zero) throw new ArgumentNullException();
string appId = DesktopManager.GetAppId(hWnd);
if (!DesktopManager.VirtualDesktopPinnedApps.IsAppIdPinned(appId))
{ // pin only if not already pinned
DesktopManager.VirtualDesktopPinnedApps.PinAppID(appId);
}
}
public static void UnpinApplication(IntPtr hWnd)
{ // unpin application for window <hWnd> from all desktops
if (hWnd == IntPtr.Zero) throw new ArgumentNullException();
var view = hWnd.GetApplicationView();
string appId = DesktopManager.GetAppId(hWnd);
if (DesktopManager.VirtualDesktopPinnedApps.IsAppIdPinned(appId))
{ // unpin only if already pinned
DesktopManager.VirtualDesktopPinnedApps.UnpinAppID(appId);
}
}
// Get window handle of current console window (even if powershell started in cmd)
[DllImport("Kernel32.dll")]
public static extern IntPtr GetConsoleWindow();
}
}
'@
function Get-DesktopCount
{
<#
.SYNOPSIS
Get count of virtual desktops
.DESCRIPTION
Get count of virtual desktops
.INPUTS
None
.OUTPUTS
Int32
.EXAMPLE
Get-DesktopCount
Get count of virtual desktops
.LINK
https://gallery.technet.microsoft.com/scriptcenter/Powershell-commands-to-d0e79cc5
.NOTES
Author: Markus Scholtes
Created: 2017/05/08
#>
return [VirtualDesktop.Desktop]::Count
}
function New-Desktop
{
<#
.SYNOPSIS
Create virtual desktop
.DESCRIPTION
Create virtual desktop
.INPUTS
None
.OUTPUTS
Desktop object
.EXAMPLE
New-Desktop | Switch-Desktop
Create virtual desktop and switch to it
.LINK
https://gallery.technet.microsoft.com/scriptcenter/Powershell-commands-to-d0e79cc5
.NOTES
Author: Markus Scholtes
Created: 2017/05/08
#>
return [VirtualDesktop.Desktop]::Create()
}
function Switch-Desktop
{
<#
.SYNOPSIS
Switch to virtual desktop
.DESCRIPTION
Switch to virtual desktop
.PARAMETER Desktop
Number of desktop (starting with 0 to count-1) or desktop object
.INPUTS
Number of desktop (starting with 0 to count-1) or desktop object
.OUTPUTS
None
.EXAMPLE
Switch-Desktop 0
Switch to first virtual desktop
.EXAMPLE
Switch-Desktop $Desktop
Switch to virtual desktop $Desktop
.EXAMPLE
New-Desktop | Switch-Desktop
Create virtual desktop and switch to it
.LINK
https://gallery.technet.microsoft.com/scriptcenter/Powershell-commands-to-d0e79cc5
.NOTES
Author: Markus Scholtes
Created: 2017/05/08
#>
[Cmdletbinding()]
Param([Parameter(ValueFromPipeline = $TRUE)] $Desktop)
if ($Desktop -is [VirtualDesktop.Desktop])
{
$Desktop.MakeVisible()
}
else
{
if ($Desktop -is [ValueType])
{
$TempDesktop = [VirtualDesktop.Desktop]::FromIndex($Desktop)
if ($TempDesktop)
{ $TempDesktop.MakeVisible() }
}
else
{
Write-Error "Parameter -Desktop has to be a Desktop object or an integer"
}
}
}
function Remove-Desktop
{
<#
.SYNOPSIS
Remove virtual desktop
.DESCRIPTION
Remove virtual desktop.
Windows on the desktop to be removed are moved to the virtual desktop to the left except for desktop 0 where the
second desktop is used instead. If the current desktop is removed, this fallback desktop is activated too.
If no desktop is supplied, the last desktop is removed.
.PARAMETER Desktop
Number of desktop (starting with 0 to count-1) or desktop object
.INPUTS
Number of desktop (starting with 0 to count-1) or desktop object
.OUTPUTS
None
.EXAMPLE
Remove-Desktop 0
Remove first virtual desktop
.EXAMPLE
Remove-Desktop $Desktop
Remove virtual desktop $Desktop
.EXAMPLE
New-Desktop | Remove-Desktop
Create virtual desktop and remove it immediately
.LINK
https://gallery.technet.microsoft.com/scriptcenter/Powershell-commands-to-d0e79cc5
.NOTES
Author: Markus Scholtes
Created: 2017/05/08
#>
[Cmdletbinding()]
Param([Parameter(ValueFromPipeline = $TRUE)] $Desktop)
if ($Desktop -eq $NULL)
{
$Desktop = [VirtualDesktop.Desktop]::FromIndex(([VirtualDesktop.Desktop]::Count) -1)
}
if ($Desktop -is [VirtualDesktop.Desktop])
{
$Desktop.Remove()
}
else
{
if ($Desktop -is [ValueType])
{
$TempDesktop = [VirtualDesktop.Desktop]::FromIndex($Desktop)
if ($TempDesktop)
{ $TempDesktop.Remove() }
}
else
{
Write-Error "Parameter -Desktop has to be a Desktop object or an integer"
}
}
}
function Get-CurrentDesktop
{
<#
.SYNOPSIS
Get current virtual desktop
.DESCRIPTION
Get current virtual desktop as Desktop object
.INPUTS
None
.OUTPUTS
Desktop object
.EXAMPLE
Get-CurrentDesktop | Remove-Desktop
Remove current virtual desktop
.LINK
https://gallery.technet.microsoft.com/scriptcenter/Powershell-commands-to-d0e79cc5
.NOTES
Author: Markus Scholtes
Created: 2017/05/08
#>
return [VirtualDesktop.Desktop]::Current
}
function Get-Desktop
{
<#
.SYNOPSIS
Get virtual desktop with index number (0 to count-1)
.DESCRIPTION
Get virtual desktop with index number (0 to count-1)
Returns $NULL if index number is out of range.
Returns current desktop is index is omitted.
.PARAMETER Index
Number of desktop (starting with 0 to count-1)
.INPUTS
Int32
.OUTPUTS
Desktop object
.EXAMPLE
Get-Desktop 1 | Switch-Desktop
Get object of second virtual desktop and switch to it
.LINK
https://gallery.technet.microsoft.com/scriptcenter/Powershell-commands-to-d0e79cc5
.NOTES
Author: Markus Scholtes
Created: 2017/05/08
#>
[Cmdletbinding()]
Param([Parameter(ValueFromPipeline = $TRUE)] $Index)
if ($Index -eq $NULL)
{
return [VirtualDesktop.Desktop]::Current
}
if ($Index -is [ValueType])
{
return [VirtualDesktop.Desktop]::FromIndex($Index)
}
else
{
Write-Error "Parameter -Index has to be an integer"
return $NULL
}
}
function Get-DesktopIndex
{
<#
.SYNOPSIS
Get index number (0 to count-1) of virtual desktop
.DESCRIPTION
Get index number (0 to count-1) of virtual desktop
Returns -1 if desktop cannot be found.
Returns index of current desktop is parameter desktop is omitted.
.PARAMETER Desktop
Desktop object
.INPUTS
Desktop object
.OUTPUTS
Int32
.EXAMPLE
New-Desktop | Get-DesktopIndex
Get index number of new virtual desktop
.LINK
https://gallery.technet.microsoft.com/scriptcenter/Powershell-commands-to-d0e79cc5
.NOTES
Author: Markus Scholtes
Created: 2017/05/08
#>
[Cmdletbinding()]
Param([Parameter(ValueFromPipeline = $TRUE)] $Desktop)
if ($Desktop -eq $NULL)
{
return [VirtualDesktop.Desktop]::FromDesktop(([VirtualDesktop.Desktop]::Current))
}
if ($Desktop -is [VirtualDesktop.Desktop])
{
return [VirtualDesktop.Desktop]::FromDesktop($Desktop)
}
else
{
Write-Error "Parameter -Desktop has to be a Desktop object"
return -1
}
}
function Get-DesktopFromWindow
{
<#
.SYNOPSIS
Get virtual desktop of window
.DESCRIPTION
Get virtual desktop of window whose window handle is given.
Returns $NULL if window handle is unknown.
.PARAMETER Hwnd
Window handle
.INPUTS
IntPtr
.OUTPUTS
Desktop object
.EXAMPLE
Get-DesktopFromWindow ((Get-Process "notepad").MainWindowHandle) | Switch-Desktop
Switch to virtual desktop with notepad window
.LINK
https://gallery.technet.microsoft.com/scriptcenter/Powershell-commands-to-d0e79cc5
.NOTES
Author: Markus Scholtes
Created: 2017/05/08
#>
[Cmdletbinding()]
Param([Parameter(ValueFromPipeline = $TRUE)] $Hwnd)
if ($Hwnd -is [IntPtr])
{
return [VirtualDesktop.Desktop]::FromWindow($Hwnd)
}
else
{
if ($Hwnd -is [ValueType])
{
return [VirtualDesktop.Desktop]::FromWindow([IntPtr]$Hwnd)
}
else
{
Write-Error "Parameter -Hwnd has to be an IntPtr or an integer"
return $NULL
}
}
}
function Test-CurrentDesktop
{
<#
.SYNOPSIS
Checks whether a desktop is the displayed virtual desktop
.DESCRIPTION
Checks whether a desktop is the displayed virtual desktop
.PARAMETER Desktop
Desktop object
.INPUTS
Desktop object
.OUTPUTS
Boolean
.EXAMPLE
Get-DesktopIndex 1 | Test-CurrentDesktop
Checks whether the desktop with count number 1 is the displayed virtual desktop
.LINK
https://gallery.technet.microsoft.com/scriptcenter/Powershell-commands-to-d0e79cc5
.NOTES
Author: Markus Scholtes
Created: 2017/05/08
#>
[Cmdletbinding()]
Param([Parameter(ValueFromPipeline = $TRUE)] $Desktop)
if ($Desktop -is [VirtualDesktop.Desktop])
{
return $Desktop.IsVisible
}
else
{
Write-Error "Parameter -Desktop has to be a Desktop object"
return $FALSE
}
}
function Get-LeftDesktop
{
<#
.SYNOPSIS
Get the desktop object on the "left" side
.DESCRIPTION
Get the desktop object on the "left" side
If there is no desktop on the "left" side $NULL is returned.
Returns desktop "left" to current desktop if parameter desktop is omitted.
.PARAMETER Desktop
Desktop object
.INPUTS
Desktop object
.OUTPUTS
Desktop object
.EXAMPLE
Get-CurrentDesktop | Get-LeftDesktop | Switch-Desktop
Switch to the desktop left to the displayed virtual desktop
.LINK
https://gallery.technet.microsoft.com/scriptcenter/Powershell-commands-to-d0e79cc5
.NOTES
Author: Markus Scholtes
Created: 2017/05/08
#>
[Cmdletbinding()]
Param([Parameter(ValueFromPipeline = $TRUE)] $Desktop)
if ($Desktop -eq $NULL)
{
return ([VirtualDesktop.Desktop]::Current).Left
}
if ($Desktop -is [VirtualDesktop.Desktop])
{
return $Desktop.Left
}
else
{
Write-Error "Parameter -Desktop has to be a Desktop object"
return $NULL
}
}
function Get-RightDesktop
{
<#
.SYNOPSIS
Get the desktop object on the "right" side
.DESCRIPTION
Get the desktop object on the "right" side
If there is no desktop on the "right" side $NULL is returned.
Returns desktop "right" to current desktop if parameter desktop is omitted.
.PARAMETER Desktop
Desktop object
.INPUTS
Desktop object
.OUTPUTS
Desktop object
.EXAMPLE
Get-CurrentDesktop | Get-RightDesktop | Switch-Desktop
Switch to the desktop right to the displayed virtual desktop
.LINK
https://gallery.technet.microsoft.com/scriptcenter/Powershell-commands-to-d0e79cc5
.NOTES
Author: Markus Scholtes
Created: 2017/05/08
#>
[Cmdletbinding()]
Param([Parameter(ValueFromPipeline = $TRUE)] $Desktop)
if ($Desktop -eq $NULL)
{
return ([VirtualDesktop.Desktop]::Current).Right
}
if ($Desktop -is [VirtualDesktop.Desktop])
{
return $Desktop.Right
}
else
{
Write-Error "Parameter -Desktop has to be a Desktop object"
return $NULL
}
}
function Move-Window
{
<#
.SYNOPSIS
Move window to virtual desktop
.DESCRIPTION
Move window whose window handle is given to virtual desktop.
The parameter values are auto detected and can change places. The desktop object is handed to the output pipeline for further use.
If parameter desktop is omitted, the current desktop is used.
.PARAMETER Desktop
Desktop object
.PARAMETER Hwnd
Window handle
.INPUTS
Desktop object
.OUTPUTS
Desktop object
.EXAMPLE
Move-Window -Desktop (Get-CurrentDesktop) -Hwnd ((Get-Process "notepad").MainWindowHandle)
Move notepad window to current virtual desktop
.EXAMPLE
New-Desktop | Move-Window (Get-ConsoleHandle) | Switch-Desktop
Create virtual desktop and move powershell console window to it, then activate new desktop.
.LINK
https://gallery.technet.microsoft.com/scriptcenter/Powershell-commands-to-d0e79cc5
.NOTES
Author: Markus Scholtes
Created: 2017/05/08
#>
[Cmdletbinding()]
Param([Parameter(ValueFromPipeline = $FALSE)] $Desktop, [Parameter(ValueFromPipeline = $TRUE)] $Hwnd)
if ($Desktop -eq $NULL)
{
$Desktop = [VirtualDesktop.Desktop]::Current
}
else
{
if ($Hwnd -eq $NULL)
{
$Hwnd = [VirtualDesktop.Desktop]::Current
}
}
if (($Hwnd -is [IntPtr]) -And ($Desktop -is [VirtualDesktop.Desktop]))
{
$Desktop.MoveWindow($Hwnd)
return $Desktop
}
if (($Hwnd -is [ValueType]) -And ($Desktop -is [VirtualDesktop.Desktop]))
{
$Desktop.MoveWindow([IntPtr]$Hwnd)
return $Desktop
}
if (($Desktop -is [IntPtr]) -And ($Hwnd -is [VirtualDesktop.Desktop]))
{
$Hwnd.MoveWindow($Desktop)
return $Hwnd
}
if (($Desktop -is [ValueType]) -And ($Hwnd -is [VirtualDesktop.Desktop]))
{
$Hwnd.MoveWindow([IntPtr]$Desktop)
return $Hwnd
}
Write-Error "Parameters -Desktop and -Hwnd have to be a Desktop object and an IntPtr/integer pair"
return $NULL
}
function Test-Window
{
<#
.SYNOPSIS
Check if window is displayed on virtual desktop
.DESCRIPTION
Check if window whose window handle is given is displayed on virtual desktop.
The parameter values are auto detected and can change places. If parameter desktop is not supplied, the current desktop is used.
.PARAMETER Desktop
Desktop object. If omitted the current desktop is used.
.PARAMETER Hwnd
Window handle
.INPUTS
Desktop object
.OUTPUTS
Boolean
.EXAMPLE
Test-Window -Hwnd ((Get-Process "notepad").MainWindowHandle)
Check if notepad window is displayed on current virtual desktop
.EXAMPLE
Get-Desktop 1 | Test-Window (Get-ConsoleHandle)
Check if powershell console window is displayed on virtual desktop with number 1 (second desktop)
.LINK
https://gallery.technet.microsoft.com/scriptcenter/Powershell-commands-to-d0e79cc5
.NOTES
Author: Markus Scholtes
Created: 2017/05/08
#>
[Cmdletbinding()]
Param([Parameter(ValueFromPipeline = $FALSE)] $Desktop, [Parameter(ValueFromPipeline = $TRUE)] $Hwnd)
if ($Hwnd -is [IntPtr])
{
if ($Desktop -is [VirtualDesktop.Desktop])
{
return $Desktop.HasWindow($Hwnd)
}
else
{
return ([VirtualDesktop.Desktop]::Current).HasWindow($Hwnd)
}
}
if ($Hwnd -is [ValueType])
{
if ($Desktop -is [VirtualDesktop.Desktop])
{
return $Desktop.HasWindow([IntPtr]$Hwnd)
}
else
{
return ([VirtualDesktop.Desktop]::Current).HasWindow([IntPtr]$Hwnd)
}
}
if ($Desktop -is [IntPtr])
{
if ($Hwnd -is [VirtualDesktop.Desktop])
{
return $Hwnd.HasWindow($Desktop)
}
else
{
return ([VirtualDesktop.Desktop]::Current).HasWindow($Desktop)
}
}
if ($Desktop -is [ValueType])
{
if ($Hwnd -is [VirtualDesktop.Desktop])
{
return $Hwnd.HasWindow([IntPtr]$Desktop)
}
else
{
return ([VirtualDesktop.Desktop]::Current).HasWindow([IntPtr]$Desktop)
}
}
Write-Error "Parameters -Desktop and -Hwnd have to be a Desktop object and an IntPtr/integer pair"
return $FALSE
}
function Pin-Window
{
<#
.SYNOPSIS
Pin window to all desktops
.DESCRIPTION
Pin window whose window handle is given to all desktops.
.PARAMETER Hwnd
Window handle
.INPUTS
IntPtr
.OUTPUTS
None
.EXAMPLE
Pin-Window ((Get-Process "notepad").MainWindowHandle)
Pin notepad window to all desktops
.LINK
https://gallery.technet.microsoft.com/scriptcenter/Powershell-commands-to-d0e79cc5
.NOTES
Author: Markus Scholtes
Created: 2017/05/08
#>
[Cmdletbinding()]
Param([Parameter(ValueFromPipeline = $TRUE)] $Hwnd)
if ($Hwnd -is [IntPtr])
{
[VirtualDesktop.Desktop]::PinWindow($Hwnd)
}
else
{
if ($Hwnd -is [ValueType])
{
[VirtualDesktop.Desktop]::PinWindow([IntPtr]$Hwnd)
}
else
{
Write-Error "Parameter -Hwnd has to be an IntPtr or an integer"
}
}
}
function Unpin-Window
{
<#
.SYNOPSIS
Unpin window from all desktops
.DESCRIPTION
Unpin window whose window handle is given from all desktops.
.PARAMETER Hwnd
Window handle
.INPUTS
IntPtr
.OUTPUTS
None
.EXAMPLE
Unpin-Window ((Get-Process "notepad").MainWindowHandle)
Unpin notepad window from all desktops
.LINK
https://gallery.technet.microsoft.com/scriptcenter/Powershell-commands-to-d0e79cc5
.NOTES
Author: Markus Scholtes
Created: 2017/05/08
#>
[Cmdletbinding()]
Param([Parameter(ValueFromPipeline = $TRUE)] $Hwnd)
if ($Hwnd -is [IntPtr])
{
[VirtualDesktop.Desktop]::UnpinWindow($Hwnd)
}
else
{
if ($Hwnd -is [ValueType])
{
[VirtualDesktop.Desktop]::UnpinWindow([IntPtr]$Hwnd)
}
else
{
Write-Error "Parameter -Hwnd has to be an IntPtr or an integer"
}
}
}
function Test-WindowPinned
{
<#
.SYNOPSIS
Checks whether a window is pinned to all desktops
.DESCRIPTION
Checks whether a window whose window handle is given is pinned to all desktops.
.PARAMETER Hwnd
Window handle
.INPUTS
IntPtr
.OUTPUTS
Boolean
.EXAMPLE
Test-WindowPinned ((Get-Process "notepad").MainWindowHandle)
Checks whether notepad window is pinned to all virtual desktops
.LINK
https://gallery.technet.microsoft.com/scriptcenter/Powershell-commands-to-d0e79cc5
.NOTES
Author: Markus Scholtes
Created: 2017/05/08
#>
[Cmdletbinding()]
Param([Parameter(ValueFromPipeline = $TRUE)] $Hwnd)
if ($Hwnd -is [IntPtr])
{
return [VirtualDesktop.Desktop]::IsWindowPinned($Hwnd)
}
else
{
if ($Hwnd -is [ValueType])
{
return [VirtualDesktop.Desktop]::IsWindowPinned([IntPtr]$Hwnd)
}
else
{
Write-Error "Parameter -Hwnd has to be an IntPtr or an integer"
return $FALSE
}
}
}
function Pin-Application
{
<#
.SYNOPSIS
Pin application to all desktops
.DESCRIPTION
Pin application whose window handle is given to all desktops.
.PARAMETER Hwnd
Window handle
.INPUTS
IntPtr
.OUTPUTS
None
.EXAMPLE
Pin-Application ((Get-Process "notepad").MainWindowHandle)
Pin all notepad windows to all desktops
.LINK
https://gallery.technet.microsoft.com/scriptcenter/Powershell-commands-to-d0e79cc5
.NOTES
Author: Markus Scholtes
Created: 2017/05/08
#>
[Cmdletbinding()]
Param([Parameter(ValueFromPipeline = $TRUE)] $Hwnd)
if ($Hwnd -is [IntPtr])
{
[VirtualDesktop.Desktop]::PinApplication($Hwnd)
}
else
{
if ($Hwnd -is [ValueType])
{
[VirtualDesktop.Desktop]::PinApplication([IntPtr]$Hwnd)
}
else
{
Write-Error "Parameter -Hwnd has to be an IntPtr or an integer"
}
}
}
function Unpin-Application
{
<#
.SYNOPSIS
Unpin application from all desktops
.DESCRIPTION
Unpin application whose window handle is given from all desktops.
.PARAMETER Hwnd
Window handle
.INPUTS
IntPtr
.OUTPUTS
None
.EXAMPLE
Unpin-Application ((Get-Process "notepad").MainWindowHandle)
Unpin all notepad windows from all desktops
.LINK
https://gallery.technet.microsoft.com/scriptcenter/Powershell-commands-to-d0e79cc5
.NOTES
Author: Markus Scholtes
Created: 2017/05/08
#>
[Cmdletbinding()]
Param([Parameter(ValueFromPipeline = $TRUE)] $Hwnd)
if ($Hwnd -is [IntPtr])
{
[VirtualDesktop.Desktop]::UnpinApplication($Hwnd)
}
else
{
if ($Hwnd -is [ValueType])
{
[VirtualDesktop.Desktop]::UnpinApplication([IntPtr]$Hwnd)
}
else
{
Write-Error "Parameter -Hwnd has to be an IntPtr or an integer"
}
}
}
function Test-ApplicationPinned
{
<#
.SYNOPSIS
Checks whether an application is pinned to all desktops
.DESCRIPTION
Checks whether an application whose window handle is given is pinned to all desktops.
.PARAMETER Hwnd
Window handle
.INPUTS
IntPtr
.OUTPUTS
Boolean
.EXAMPLE
Test-ApplicationPinned ((Get-Process "notepad").MainWindowHandle)
Checks whether notepad windows are pinned to all virtual desktops
.LINK
https://gallery.technet.microsoft.com/scriptcenter/Powershell-commands-to-d0e79cc5
.NOTES
Author: Markus Scholtes
Created: 2017/05/08
#>
[Cmdletbinding()]
Param([Parameter(ValueFromPipeline = $TRUE)] $Hwnd)
if ($Hwnd -is [IntPtr])
{
return [VirtualDesktop.Desktop]::IsApplicationPinned($Hwnd)
}
else
{
if ($Hwnd -is [ValueType])
{
return [VirtualDesktop.Desktop]::IsApplicationPinned([IntPtr]$Hwnd)
}
else
{
Write-Error "Parameter -Hwnd has to be an IntPtr or an integer"
return $FALSE
}
}
}
function Get-ConsoleHandle
{
<#
.SYNOPSIS
Get window handle of powershell console
.DESCRIPTION
Get window handle of powershell console in a safe way (means: if powershell is started in a cmd window, the cmd window handled is returned)
.INPUTS
None
.OUTPUTS
IntPtr
.EXAMPLE
Get-ConsoleHandle
Get window handle of powershell console
.LINK
https://gallery.technet.microsoft.com/scriptcenter/Powershell-commands-to-d0e79cc5
.NOTES
Author: Markus Scholtes
Created: 2017/05/08
#>
return [VirtualDesktop.Desktop]::GetConsoleWindow()
}
<#
$KeyShortcut = Add-Type -MemberDefinition @"
[DllImport("user32.dll")]
static extern void keybd_event(byte bVk, byte bScan, uint dwFlags, UIntPtr dwExtraInfo);
//WIN + CTRL + D: Create a new desktop
public static void CreateVirtualDesktopInWin10()
{
//Key down
keybd_event((byte)0x5B, 0, 0, UIntPtr.Zero); //Left Windows key
keybd_event((byte)0x11, 0, 0, UIntPtr.Zero); //CTRL
keybd_event((byte)0x39, 0, 0, UIntPtr.Zero); //right
//Key up
keybd_event((byte)0x5B, 0, (uint)0x2, UIntPtr.Zero);
keybd_event((byte)0x11, 0, (uint)0x2, UIntPtr.Zero);
keybd_event((byte)0x39, 0, (uint)0x2, UIntPtr.Zero);
}
"@ -Name VirtualDekstopGoRight -UsingNamespace System.Threading -PassThru
$KeyShortcut = Add-Type -MemberDefinition @"
[DllImport("user32.dll")]
static extern void keybd_event(byte bVk, byte bScan, uint dwFlags, UIntPtr dwExtraInfo);
//WIN + CTRL + D: Create a new desktop
public static void CreateVirtualDesktopInWin10()
{
//Key down
keybd_event((byte)0x5B, 0, 0, UIntPtr.Zero); //Left Windows key
keybd_event((byte)0x11, 0, 0, UIntPtr.Zero); //CTRL
keybd_event((byte)0x39, 0, 0, UIntPtr.Zero); //right
//Key up
keybd_event((byte)0x5B, 0, (uint)0x2, UIntPtr.Zero);
keybd_event((byte)0x11, 0, (uint)0x2, UIntPtr.Zero);
keybd_event((byte)0x39, 0, (uint)0x2, UIntPtr.Zero);
}
"@ -Name VirtualDekstopGoLeft -UsingNamespace System.Threading -PassThru
$KeyShortcut::VirtualDesktopGoRight()
#>
$currentdesktop = get-currentdesktop
if(($currentdesktop.right -eq $null) -or ($currentdesktop.right -eq "")) {
$switchdesktop = get-desktop 0
Switch-Desktop $switchdesktop
} else {
Switch-Desktop $currentdesktop.right
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment