通过命令行设置PowerShell的不透明度是否可行?

4

我是新手,对PowerShell和.NET不太熟悉。

可以配置PowerShell控制台颜色。

但是如何设置窗口的透明度呢?似乎InternalHostRawUserInterface类的属性采用枚举ConsoleColor

有没有可能设置窗口的透明度呢?


1
是的。如果需要的话,可以使用一些自定义的C#代码来执行P/Invoke操作。你的问题是不是“我该如何做到这一点?”? - Joey
2个回答

12

正如在Joey的评论中所提到的,您需要与低级API交互来修改窗口的透明度。

使用这个示例,我们可以将其适配到PowerShell中,如下所示:

function Set-ConsoleOpacity
{
    param(
        [ValidateRange(10,100)]
        [int]$Opacity
    )

    # Check if pinvoke type already exists, if not import the relevant functions
    try {
        $Win32Type = [Win32.WindowLayer]
    } catch {
        $Win32Type = Add-Type -MemberDefinition @'
            [DllImport("user32.dll")]
            public static extern int SetWindowLong(IntPtr hWnd, int nIndex, int dwNewLong);

            [DllImport("user32.dll")]
            public static extern int GetWindowLong(IntPtr hWnd, int nIndex);

            [DllImport("user32.dll")]
            public static extern bool SetLayeredWindowAttributes(IntPtr hwnd, uint crKey, byte bAlpha, uint dwFlags);
'@ -Name WindowLayer -Namespace Win32 -PassThru
    }

    # Calculate opacity value (0-255)
    $OpacityValue = [int]($Opacity * 2.56) - 1

    # Grab the host windows handle
    $ThisProcess = Get-Process -Id $PID
    $WindowHandle = $ThisProcess.MainWindowHandle

    # "Constants"
    $GwlExStyle  = -20;
    $WsExLayered = 0x80000;
    $LwaAlpha    = 0x2;

    if($Win32Type::GetWindowLong($WindowHandle,-20) -band $WsExLayered -ne $WsExLayered){
        # If Window isn't already marked "Layered", make it so
        [void]$Win32Type::SetWindowLong($WindowHandle,$GwlExStyle,$Win32Type::GetWindowLong($WindowHandle,$GwlExStyle) -bxor $WsExLayered)
    }

    # Set transparency
    [void]$Win32Type::SetLayeredWindowAttributes($WindowHandle,0,$OpacityValue,$LwaAlpha)
}

然后像这样使用它:

Set-ConsoleOpacity -Opacity 50

接下来将会把窗口的透明度设置为50%。


在真正的PowerShell中运行。当从cmd启动PowerShell时无法运行。我的使用方式:script.ps1.cmd,在每个主机上允许拖放到.cmd。不幸啊 :D。 - Joachim Otahal

0
按住 Ctrl 和 Shift 键,然后滚动鼠标滚轮。这可能是一个无用的答案,我不确定这是否是一个永久设置。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接