【问题标题】:How to change the Console Ouptut Mode using SetConsoleMode in powershell?如何在 powershell 中使用 SetConsoleMode 更改控制台输出模式?
【发布时间】:2019-05-14 03:40:48
【问题描述】:

我正在尝试使用 Windows API 和 SetConsoleMode 调用更改 输出 (CONOUT$) 的 Windows 控制台模式。因此,我修改了一个基于ConinMode.ps1(适用于input)的PowerShell 脚本来执行此操作。 ReadingConoutMode.exe 和我的脚本都可以正常工作,并返回:

# .\ConoutMode.exe
mode: 0x3
ENABLE_PROCESSED_OUTPUT            0x0001 ON
ENABLE_WRAP_AT_EOL_OUTPUT          0x0002 ON
ENABLE_VIRTUAL_TERMINAL_PROCESSING 0x0004 off   <====
DISABLE_NEWLINE_AUTO_RETURN        0x0008 off
ENABLE_LVB_GRID_WORLDWIDE          0x0010 off

# .\ConoutMode.ps1
OK! GetConsoleWindow handle  :  0x1F06D6
Console Input  Mode (CONIN)  :  0x21f
Console Output Mode (CONOUT) :  0x3

但是,我的脚本和 exe 都无法写入模式。 (可能是因为它认为我的输出句柄没有指向控制台?)

在 PowerShell 中:

# .\ConoutMode.exe set 0x000f
error: SetConsoleMode failed (is stdout a console?)

# .\ConoutMode.ps1 -Mode 7
OK! GetConsoleWindow handle  :  0x1F06D6
old (out) mode: 0x3
SetConsoleMode (out) failed (is stdout a console?)
At C:\cygwin64\home\emix\win_esc_test\ConoutMode.ps1:112 char:9
+         throw "SetConsoleMode (out) failed (is stdout a console?)"
+         ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo          : OperationStopped: (SetConsoleMode ...out a console?):String) [], RuntimeException
+ FullyQualifiedErrorId : SetConsoleMode (out) failed (is stdout a console?)

这是我的完整的ConoutMode.ps1 脚本:

param (
    [int] $Mode
)

$signature = @'
[DllImport("kernel32.dll", SetLastError=true)]
public static extern IntPtr GetConsoleWindow();

[DllImport("kernel32.dll", SetLastError = true)]
public static extern IntPtr GetStdHandle(int nStdHandle);

[DllImport("kernel32.dll", SetLastError = true)]
public static extern uint GetConsoleMode(IntPtr hConsoleHandle, out uint lpMode);

[DllImport("kernel32.dll", SetLastError = true)]
public static extern uint SetConsoleMode(IntPtr hConsoleHandle, uint dwMode);

public const int STD_INPUT_HANDLE  = -10;
public const int STD_OUTPUT_HANDLE = -11;

public const int  ENABLE_PROCESSED_OUTPUT            = 0x0001;
public const int  ENABLE_WRAP_AT_EOL_OUTPUT          = 0x0002;
public const int  ENABLE_VIRTUAL_TERMINAL_PROCESSING = 0x0004;
public const int  DISABLE_NEWLINE_AUTO_RETURN        = 0x0008;
public const int  ENABLE_LVB_GRID_WORLDWIDE          = 0x0010;
'@
#----------------------------------------------------------
$WinAPI = Add-Type -MemberDefinition $signature -Name WinAPI -Namespace ConoutMode -PassThru
#$WinAPI = Add-Type -MemberDefinition $signature -Name WinAPI -Namespace IdentifyConsoleWindow -PassThru

$hwnd = $WinAPI::GetConsoleWindow()
if ($hwnd -eq 0) {
    throw "Error: GetConsoleWindow returned NULL."
} 
echo "OK! GetConsoleWindow handle  :  0x$($hwnd.ToString("X"))"

function GetConIn {
    $ret = $WinAPI::GetStdHandle($WinAPI::STD_INPUT_HANDLE)
    if ($ret -eq -1) {
        throw "Error: cannot get stdin handle"
    }
    return $ret
}

function GetConOut {
    $ret = $WinAPI::GetStdHandle($WinAPI::STD_OUTPUT_HANDLE)
    if ($ret -eq -1) {
        throw "Error: cannot get stdout handle"
    }
    return $ret
}

function GetConInMode { #GetCOnsoleMode
    $conin = GetConIn
    $mode = 0
    $ret = $WinAPI::GetConsoleMode($conin, [ref]$mode)
    if ($ret -eq 0) {
        throw "GetConsoleMode (in) failed (is stdin a console?)"
    }
    return $mode
}

function GetConOutMode {
    $conout = GetConOut
    $mode   = 0
    $ret    = $WinAPI::GetConsoleMode($conout, [ref]$mode)
    if ($ret -eq 0) {
        throw "GetConsoleMode (out) failed (is stdout a console?)"
    }
    return $mode
}

function SetConInMode($mode) {
    $conin = GetConIn
    $ret = $WinAPI::SetConsoleMode($conin, $mode)
    if ($ret -eq 0) {
        throw "SetConsoleMode (in) failed (is stdin a console?)"
    }
}

function SetConOutMode($mode) {
    #$conout = GetConOut
    # Different tack:
    $conout = $hwnd
    $ret = $WinAPI::SetConsoleMode($conout, $mode)
    if ($ret -eq 0) {
        throw "SetConsoleMode (out) failed (is stdout a console?)"
    }
}

#----------------------------------------------------------
# MAIN
#----------------------------------------------------------
$oldInMode  = GetConInMode
$oldOutMode = GetConOutMode

$newMode = $oldOutMode
$doit = $false

if ($PSBoundParameters.ContainsKey("Mode")) {
    $newMode = $Mode
    $doit = $true
}

if ($doit) {
    echo "old (out) mode: 0x$($oldOutMode.ToString("x"))"
    SetConOutMode $newMode
    $newMode = GetConOutMode
    echo "new (out) mode: 0x$($newMode.ToString("x"))"
} else {
    echo "Console Input  Mode (CONIN)  :  0x$($oldInMode.ToString("x"))"
    echo "Console Output Mode (CONOUT) :  0x$($oldOutMode.ToString("x"))"
}

所以说到底,我想为控制台启用 ENABLE_VIRTUAL_TERMINAL_PROCESSING

我使用的系统是:

---------------------------------------------------------
  PowerShell Version    : 6.1.1
  OS Name               : Microsoft Windows 8.1 (64-bit)
  OS Version            : 6.3.9600  [2018-11-16 00:50:01]
  OS BuildLabEx         : 9600.19179
  OS HAL                : 6.3.9600.18969
  OS Kernel             : 6.3.9600.18217
  OS UBR                : 19182
  -------------------------------------------------------
  with Privilege        : Administrator
  -------------------------------------------------------
  ExecutionPolicy :
        MachinePolicy   : Undefined
        UserPolicy      : Undefined
        Process         : Undefined
        CurrentUser     : Undefined
        LocalMachine    : Bypass

  Console Settings:
      Type              : ConsoleHost
      OutputEncoding    : Unicode (UTF-8)
      Color Capability  : 23
      Registry VT Level : 1
      CodePage (input)  : 437
      CodePage (output) : 437

我还按照其他地方的说明启用了注册表项:HKCU:\Console\VirtualTerminalLevel


问:如何使用 PowerShell 启用此位/标志?

我能想到的一些事情可能是错误的:

  • 我肯定对它的工作原理有错误的理解......
  • 我可能有错误的permissions 写入控制台? (如何设置?)
  • 我可能不会写入correct 输出缓冲区? (怎么找?)

    请注意,设置一个屏幕缓冲区的输出模式不会影响其他屏幕缓冲区的输出模式。

  • 执行脚本时,是否会创建一个新的输出缓冲区? (怎么办?)

  • 我可能需要create a new 缓冲?
  • 我可能需要create a new 控制台?

相关问题和链接:

【问题讨论】:

  • 在我看来,您在调用 SetConsoleMode 时使用了错误的句柄。 GetConsoleWindow 与 GetStdHandle
  • 我都试过了,还有很多其他的东西。
  • GetLastError 报告了什么?另外,编辑您的问题并删除 GetConsoleWindow,使用此功能永远不正确。
  • @Anders 抱歉,我不明白你的意思。最后一个错误是上面显示的错误。如果有另一种方式,IDK 怎么读。还有我刚才用的GetConsoleWindow看看有没有其他的windowslike here

标签: powershell winapi console-application windows-console


【解决方案1】:

我自己已经对此进行了几天的试验,并开始意识到一些事情。显然 PowerShell 在启动时启用了虚拟终端处理。但是,它会在启动可执行文件时再次禁用它,然后在可执行文件退出时重新启用它。这意味着任何需要虚拟终端处理的可执行文件都必须自己启用它,或者通过启用它的包装程序调用它,然后通过管道将 stdin/stdout/stderr 传递到终端。至于如何编写这样的程序,我不知道。

【讨论】:

【解决方案2】:

代码使用“GetStdHandle”来获取标准输入或标准输出。而那些可能是控制台句柄——但这取决于进程的创建方式。如果您是从控制台启动的,并且 stdin/stdout 没有被重定向,那么您可能会得到一个控制台句柄。但不能保证。

与其要求 stdin/stdout,不如直接打开控制台句柄 - 您可以为 CONIN$CONOUT$“创建文件”。 CreateFile 的文档有a whole section on Consoles


更新:我制作了 a Gist 来演示如何使用 CreateFile 从 PowerShell 打开 CONIN$CONOUT$

【讨论】:

    猜你喜欢
    • 2015-04-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-29
    • 2012-01-10
    相关资源
    最近更新 更多