ruby 2.3.1p112 (2016-04-26 revision 54768) [x64-mingw32]
在 Windows 10 上使用,版本10.0.14393
.
先说几点:
- Windows
echo
命令的行为绕过了 VT100 的控制台模式标志。根据 MSDN,这是正常的,其中标志仅影响WriteConsole()
和WriteFile()
。 WriteConsole()
当我使用 更改标志时,Win32 功能正常工作SetConsoleMode()
。它在设置标志时解释 VT100 转义序列。
那么Ruby到底怎么了?它以绿色显示红色并以某种方式忽略了我的控制台标志。另外为什么它显示更深的绿色?我的理论是,这是 Ruby 的一个问题,以及它如何处理将输出写入控制台。
完整脚本:
#!/usr/bin/ruby
# encoding: UTF-8
require 'rbconfig'
unless RbConfig::CONFIG['host_os'] =~ /mswin|mingw|cygwin/
raise 'This script only works on Windows. Quitting.'
end
require 'fiddle'
require 'fiddle/types'
require 'fiddle/import'
class VirtMode
#TODO: Check Windows 10 build number (>= 1511) for mode support
module Kernel32
extend Fiddle::Importer
dlload 'kernel32'
include Fiddle::Win32Types
DWORD_SIZE = sizeof('DWORD')
STD_OUTPUT_HANDLE = -11
STD_INPUT_HANDLE = -10
VIRTUAL_TERMINAL_PROCESSING = 0x0004
extern 'HANDLE GetStdHandle(DWORD)'
extern 'DWORD SetConsoleMode(HANDLE, DWORD)'
extern 'DWORD GetConsoleMode(HANDLE, PDWORD)'
extern 'BOOL WriteConsole(HANDLE, const *char, DWORD, PDWORD, PVOID)'
end
class << self; attr_accessor :stdout, :stdin end
self.stdout = Kernel32::GetStdHandle(Kernel32::STD_OUTPUT_HANDLE)
self.stdin = Kernel32::GetStdHandle(Kernel32::STD_INPUT_HANDLE)
def self.get_mode
mode = [0].pack('L')
success = Kernel32::GetConsoleMode(stdout, mode)
return mode.unpack('L').first if success.nonzero?
raise 'Could not get console mode'
end
def self.enable_virtual_mode
new_mode = get_mode | Kernel32::VIRTUAL_TERMINAL_PROCESSING
#puts new_mode.to_s(2).rjust(32, '0')
return Kernel32::SetConsoleMode(stdout, new_mode).nonzero?
end
def self.disable_virtual_mode
new_mode = get_mode & ~Kernel32::VIRTUAL_TERMINAL_PROCESSING
#puts new_mode.to_s(2).rjust(32, '0')
return Kernel32::SetConsoleMode(stdout, new_mode).nonzero?
end
def self.write_console(text)
written = 0
Kernel32::WriteConsole(stdout, text, text.size, written, 0)
end
end
# It's already disabled but just in case
VirtMode.disable_virtual_mode
puts '--VT100 mode disabled--'
puts "\e[38;2;255;0;32mRuby: Red!\e[0m"
VirtMode.write_console "\e[38;2;255;0;32mWin32: Red!\e[0m\n"
system "echo \e[38;2;255;0;32mEcho: Red!\e[0m\n"
# Now we enable Windows 10 support for VT100
# https://msdn.microsoft.com/en-us/library/windows/desktop/mt638032(v=vs.85).aspx
VirtMode.enable_virtual_mode
puts '--VT100 mode enabled--'
puts "\e[38;2;0;255;32mRuby: Green!\e[0m"
VirtMode.write_console "\e[38;2;0;255;32mWin32: Green!\e[0m\n"
system "echo \e[38;2;0;255;32mEcho: Green!\e[0m\n"
不要在 Rubymine 中调试此脚本,除非您已将其输出到 Windows 控制台,例如 PowerShell 或命令提示符,GetConsoleMode()
否则会失败。