2 using Microsoft.Win32.SafeHandles;
18 internal enum ControlKeyState
20 RightAltPressed = 0x1,
22 RightCtrlPressed = 0x4,
23 LeftCtrlPressed = 0x8,
36 private Win32Native.ConsoleCtrlHandlerRoutine _handler;
39 internal ControlCHooker()
41 _handler = BreakEvent;
49 [SecuritySafeCritical]
54 if (!Win32Native.SetConsoleCtrlHandler(_handler, addOrRemove:
true))
62 [SecuritySafeCritical]
63 [ReliabilityContract(
Consistency.WillNotCorruptState,
Cer.Success)]
64 internal void Unhook()
68 if (!Win32Native.SetConsoleCtrlHandler(_handler, addOrRemove:
false))
77 private sealed
class ControlCDelegateData
83 internal bool DelegateStarted;
91 ControlKey = controlKey;
92 CancelCallbacks = cancelCallbacks;
97 private const int DefaultConsoleBufferSize = 256;
99 private const short AltVKCode = 18;
101 private const int NumberLockVKCode = 144;
103 private const int CapsLockVKCode = 20;
105 private const int MinBeepFrequency = 37;
107 private const int MaxBeepFrequency = 32767;
109 private const int MaxConsoleTitleLength = 24500;
121 private static volatile ControlCHooker _hooker;
124 private static Win32Native.InputRecord _cachedInputRecord;
126 private static volatile bool _haveReadDefaultColors;
128 private static volatile byte _defaultColors;
130 private static volatile bool _isOutTextWriterRedirected =
false;
132 private static volatile bool _isErrorTextWriterRedirected =
false;
134 private static volatile Encoding _inputEncoding =
null;
136 private static volatile Encoding _outputEncoding =
null;
138 private static volatile bool _stdInRedirectQueried =
false;
140 private static volatile bool _stdOutRedirectQueried =
false;
142 private static volatile bool _stdErrRedirectQueried =
false;
144 private static bool _isStdInRedirected;
146 private static bool _isStdOutRedirected;
148 private static bool _isStdErrRedirected;
150 private static volatile object s_InternalSyncObject;
152 private static volatile object s_ReadKeySyncObject;
154 private static volatile IntPtr _consoleInputHandle;
156 private static volatile IntPtr _consoleOutputHandle;
158 private static object InternalSyncObject
162 if (s_InternalSyncObject ==
null)
164 object value =
new object();
167 return s_InternalSyncObject;
171 private static object ReadKeySyncObject
175 if (s_ReadKeySyncObject ==
null)
177 object value =
new object();
180 return s_ReadKeySyncObject;
184 private static IntPtr ConsoleInputHandle
191 _consoleInputHandle = Win32Native.GetStdHandle(-10);
193 return _consoleInputHandle;
197 private static IntPtr ConsoleOutputHandle
204 _consoleOutputHandle = Win32Native.GetStdHandle(-11);
206 return _consoleOutputHandle;
215 [SecuritySafeCritical]
218 if (_stdInRedirectQueried)
220 return _isStdInRedirected;
222 lock (InternalSyncObject)
224 if (_stdInRedirectQueried)
226 return _isStdInRedirected;
228 _isStdInRedirected = IsHandleRedirected(ConsoleInputHandle);
229 _stdInRedirectQueried =
true;
230 return _isStdInRedirected;
240 [SecuritySafeCritical]
243 if (_stdOutRedirectQueried)
245 return _isStdOutRedirected;
247 lock (InternalSyncObject)
249 if (_stdOutRedirectQueried)
251 return _isStdOutRedirected;
253 _isStdOutRedirected = IsHandleRedirected(ConsoleOutputHandle);
254 _stdOutRedirectQueried =
true;
255 return _isStdOutRedirected;
265 [SecuritySafeCritical]
268 if (_stdErrRedirectQueried)
270 return _isStdErrRedirected;
272 lock (InternalSyncObject)
274 if (_stdErrRedirectQueried)
276 return _isStdErrRedirected;
278 IntPtr stdHandle = Win32Native.GetStdHandle(-12);
279 _isStdErrRedirected = IsHandleRedirected(stdHandle);
280 _stdErrRedirectQueried =
true;
281 return _isStdErrRedirected;
290 [SecuritySafeCritical]
296 lock (InternalSyncObject)
329 InitializeStdOutError(stdout:
true);
344 InitializeStdOutError(stdout:
false);
357 [SecuritySafeCritical]
360 if (_inputEncoding !=
null)
362 return _inputEncoding;
364 lock (InternalSyncObject)
366 if (_inputEncoding !=
null)
368 return _inputEncoding;
370 uint consoleCP = Win32Native.GetConsoleCP();
372 return _inputEncoding;
375 [SecuritySafeCritical]
383 lock (InternalSyncObject)
385 if (!IsStandardConsoleUnicodeEncoding(value))
387 uint codePage = (uint)value.CodePage;
388 if (!Win32Native.SetConsoleCP(codePage))
390 __Error.WinIOError();
393 _inputEncoding = (
Encoding)value.Clone();
406 [SecuritySafeCritical]
409 if (_outputEncoding !=
null)
411 return _outputEncoding;
413 lock (InternalSyncObject)
415 if (_outputEncoding !=
null)
417 return _outputEncoding;
419 uint consoleOutputCP = Win32Native.GetConsoleOutputCP();
421 return _outputEncoding;
424 [SecuritySafeCritical]
432 lock (InternalSyncObject)
434 if (_out !=
null && !_isOutTextWriterRedirected)
439 if (_error !=
null && !_isErrorTextWriterRedirected)
444 if (!IsStandardConsoleUnicodeEncoding(value))
446 uint codePage = (uint)value.CodePage;
447 if (!Win32Native.SetConsoleOutputCP(codePage))
449 __Error.WinIOError();
452 _outputEncoding = (
Encoding)value.Clone();
464 [SecuritySafeCritical]
468 Win32Native.CONSOLE_SCREEN_BUFFER_INFO bufferInfo = GetBufferInfo(throwOnNoConsole:
false, out succeeded);
473 Win32Native.Color c = (Win32Native.Color)(bufferInfo.wAttributes & 0xF0);
474 return ColorAttributeToConsoleColor(c);
476 [SecuritySafeCritical]
480 Win32Native.Color color = ConsoleColorToColorAttribute(value, isBackground:
true);
482 Win32Native.CONSOLE_SCREEN_BUFFER_INFO bufferInfo = GetBufferInfo(throwOnNoConsole:
false, out succeeded);
485 short wAttributes = bufferInfo.wAttributes;
486 wAttributes = (short)(wAttributes & -241);
487 wAttributes = (short)((ushort)wAttributes | (ushort)color);
488 Win32Native.SetConsoleTextAttribute(ConsoleOutputHandle, wAttributes);
500 [SecuritySafeCritical]
504 Win32Native.CONSOLE_SCREEN_BUFFER_INFO bufferInfo = GetBufferInfo(throwOnNoConsole:
false, out succeeded);
509 Win32Native.Color c = (Win32Native.Color)(bufferInfo.wAttributes & 0xF);
510 return ColorAttributeToConsoleColor(c);
512 [SecuritySafeCritical]
516 Win32Native.Color color = ConsoleColorToColorAttribute(value, isBackground:
false);
518 Win32Native.CONSOLE_SCREEN_BUFFER_INFO bufferInfo = GetBufferInfo(throwOnNoConsole:
false, out succeeded);
521 short wAttributes = bufferInfo.wAttributes;
522 wAttributes = (short)(wAttributes & -16);
523 wAttributes = (short)((ushort)wAttributes | (ushort)color);
524 Win32Native.SetConsoleTextAttribute(ConsoleOutputHandle, wAttributes);
536 [SecuritySafeCritical]
539 Win32Native.CONSOLE_SCREEN_BUFFER_INFO bufferInfo = GetBufferInfo();
540 return bufferInfo.dwSize.Y;
555 [SecuritySafeCritical]
558 Win32Native.CONSOLE_SCREEN_BUFFER_INFO bufferInfo = GetBufferInfo();
559 return bufferInfo.dwSize.X;
573 [SecuritySafeCritical]
576 Win32Native.CONSOLE_SCREEN_BUFFER_INFO bufferInfo = GetBufferInfo();
577 return bufferInfo.srWindow.Bottom - bufferInfo.srWindow.Top + 1;
591 [SecuritySafeCritical]
594 Win32Native.CONSOLE_SCREEN_BUFFER_INFO bufferInfo = GetBufferInfo();
595 return bufferInfo.srWindow.Right - bufferInfo.srWindow.Left + 1;
607 [SecuritySafeCritical]
610 Win32Native.COORD largestConsoleWindowSize = Win32Native.GetLargestConsoleWindowSize(ConsoleOutputHandle);
611 return largestConsoleWindowSize.X;
619 [SecuritySafeCritical]
622 Win32Native.COORD largestConsoleWindowSize = Win32Native.GetLargestConsoleWindowSize(ConsoleOutputHandle);
623 return largestConsoleWindowSize.Y;
633 [SecuritySafeCritical]
636 Win32Native.CONSOLE_SCREEN_BUFFER_INFO bufferInfo = GetBufferInfo();
637 return bufferInfo.srWindow.Left;
651 [SecuritySafeCritical]
654 Win32Native.CONSOLE_SCREEN_BUFFER_INFO bufferInfo = GetBufferInfo();
655 return bufferInfo.srWindow.Top;
670 [SecuritySafeCritical]
673 Win32Native.CONSOLE_SCREEN_BUFFER_INFO bufferInfo = GetBufferInfo();
674 return bufferInfo.dwCursorPosition.X;
689 [SecuritySafeCritical]
692 Win32Native.CONSOLE_SCREEN_BUFFER_INFO bufferInfo = GetBufferInfo();
693 return bufferInfo.dwCursorPosition.Y;
708 [SecuritySafeCritical]
711 IntPtr consoleOutputHandle = ConsoleOutputHandle;
712 if (!Win32Native.GetConsoleCursorInfo(consoleOutputHandle, out Win32Native.CONSOLE_CURSOR_INFO cci))
714 __Error.WinIOError();
718 [SecuritySafeCritical]
721 if (value < 1 || value > 100)
726 IntPtr consoleOutputHandle = ConsoleOutputHandle;
727 if (!Win32Native.GetConsoleCursorInfo(consoleOutputHandle, out Win32Native.CONSOLE_CURSOR_INFO cci))
729 __Error.WinIOError();
732 if (!Win32Native.SetConsoleCursorInfo(consoleOutputHandle, ref cci))
734 __Error.WinIOError();
746 [SecuritySafeCritical]
749 IntPtr consoleOutputHandle = ConsoleOutputHandle;
750 if (!Win32Native.GetConsoleCursorInfo(consoleOutputHandle, out Win32Native.CONSOLE_CURSOR_INFO cci))
752 __Error.WinIOError();
756 [SecuritySafeCritical]
760 IntPtr consoleOutputHandle = ConsoleOutputHandle;
761 if (!Win32Native.GetConsoleCursorInfo(consoleOutputHandle, out Win32Native.CONSOLE_CURSOR_INFO cci))
763 __Error.WinIOError();
765 cci.bVisible = value;
766 if (!Win32Native.SetConsoleCursorInfo(consoleOutputHandle, ref cci))
768 __Error.WinIOError();
779 public static string Title 781 [SecuritySafeCritical]
785 int outTitleLength = -1;
786 int titleNative = GetTitleNative(JitHelpers.GetStringHandleOnStack(ref s), out outTitleLength);
787 if (titleNative != 0)
789 __Error.WinIOError(titleNative,
string.Empty);
791 if (outTitleLength > 24500)
797 [SecuritySafeCritical]
804 if (value.Length > 24500)
809 if (!Win32Native.SetConsoleTitle(value))
811 __Error.WinIOError();
823 [SecuritySafeCritical]
827 if (_cachedInputRecord.eventType == 1)
831 Win32Native.InputRecord buffer =
default(Win32Native.InputRecord);
832 int numEventsRead = 0;
835 if (!Win32Native.PeekConsoleInput(ConsoleInputHandle, out buffer, 1, out numEventsRead))
838 if (lastWin32Error == 6)
842 __Error.WinIOError(lastWin32Error,
"stdin");
844 if (numEventsRead == 0)
848 if (IsKeyDownEvent(buffer) && !IsModKey(buffer))
852 if (!Win32Native.ReadConsoleInput(ConsoleInputHandle, out buffer, 1, out numEventsRead))
854 __Error.WinIOError();
866 [SecuritySafeCritical]
869 short keyState = Win32Native.GetKeyState(144);
870 return (keyState & 1) == 1;
879 [SecuritySafeCritical]
882 short keyState = Win32Native.GetKeyState(20);
883 return (keyState & 1) == 1;
893 [SecuritySafeCritical]
896 IntPtr consoleInputHandle = ConsoleInputHandle;
897 if (consoleInputHandle == Win32Native.INVALID_HANDLE_VALUE)
902 if (!Win32Native.GetConsoleMode(consoleInputHandle, out mode))
904 __Error.WinIOError();
906 return (mode & 1) == 0;
908 [SecuritySafeCritical]
912 IntPtr consoleInputHandle = ConsoleInputHandle;
913 if (consoleInputHandle == Win32Native.INVALID_HANDLE_VALUE)
918 bool consoleMode = Win32Native.GetConsoleMode(consoleInputHandle, out mode);
919 mode = ((!value) ? (mode | 1) : (mode & -2));
920 if (!Win32Native.SetConsoleMode(consoleInputHandle, mode))
922 __Error.WinIOError();
930 [SecuritySafeCritical]
934 lock (InternalSyncObject)
939 _hooker =
new ControlCHooker();
944 [SecuritySafeCritical]
948 lock (InternalSyncObject)
951 if (_hooker !=
null && _cancelCallbacks ==
null)
959 [SecuritySafeCritical]
960 private static bool IsHandleRedirected(
IntPtr ioHandle)
962 SafeFileHandle handle =
new SafeFileHandle(ioHandle, ownsHandle:
false);
963 int fileType = Win32Native.GetFileType(handle);
964 if ((fileType & 2) != 2)
969 bool consoleMode = Win32Native.GetConsoleMode(ioHandle, out mode);
973 [SecuritySafeCritical]
974 private static void InitializeStdOutError(
bool stdout)
976 lock (InternalSyncObject)
978 if ((!stdout || _out ==
null) && (stdout || _error ==
null))
990 streamWriter.HaveWrittenPreamble =
true;
1000 _error = textWriter;
1006 private static bool IsStandardConsoleUnicodeEncoding(
Encoding encoding)
1009 if (unicodeEncoding ==
null)
1013 if (StdConUnicodeEncoding.CodePage == unicodeEncoding.
CodePage)
1015 return StdConUnicodeEncoding.bigEndian == unicodeEncoding.bigEndian;
1020 private static bool GetUseFileAPIs(
int handleType)
1047 [SecuritySafeCritical]
1048 private static Stream GetStandardFile(
int stdHandleName,
FileAccess access,
int bufferSize)
1050 IntPtr stdHandle = Win32Native.GetStdHandle(stdHandleName);
1051 SafeFileHandle safeFileHandle =
new SafeFileHandle(stdHandle, ownsHandle:
false);
1052 if (safeFileHandle.IsInvalid)
1054 safeFileHandle.SetHandleAsInvalid();
1057 if (stdHandleName != -10 && !ConsoleHandleIsWritable(safeFileHandle))
1061 bool useFileAPIs = GetUseFileAPIs(stdHandleName);
1062 return new __ConsoleStream(safeFileHandle, access, useFileAPIs);
1065 [SecuritySafeCritical]
1066 private unsafe
static bool ConsoleHandleIsWritable(SafeFileHandle outErrHandle)
1069 int numBytesWritten;
1070 int num = Win32Native.WriteFile(outErrHandle, &b, 0, out numBytesWritten, IntPtr.Zero);
1089 [SecuritySafeCritical]
1091 public static void Beep(
int frequency,
int duration)
1093 if (frequency < 37 || frequency > 32767)
1101 Win32Native.Beep(frequency, duration);
1106 [SecuritySafeCritical]
1109 Win32Native.COORD cOORD =
default(Win32Native.COORD);
1110 IntPtr consoleOutputHandle = ConsoleOutputHandle;
1111 if (consoleOutputHandle == Win32Native.INVALID_HANDLE_VALUE)
1115 Win32Native.CONSOLE_SCREEN_BUFFER_INFO bufferInfo = GetBufferInfo();
1116 int num = bufferInfo.dwSize.X * bufferInfo.dwSize.Y;
1117 int pNumCharsWritten = 0;
1118 if (!Win32Native.FillConsoleOutputCharacter(consoleOutputHandle,
' ', num, cOORD, out pNumCharsWritten))
1120 __Error.WinIOError();
1122 pNumCharsWritten = 0;
1123 if (!Win32Native.FillConsoleOutputAttribute(consoleOutputHandle, bufferInfo.wAttributes, num, cOORD, out pNumCharsWritten))
1125 __Error.WinIOError();
1127 if (!Win32Native.SetConsoleCursorPosition(consoleOutputHandle, cOORD))
1129 __Error.WinIOError();
1134 private static Win32Native.Color ConsoleColorToColorAttribute(
ConsoleColor color,
bool isBackground)
1140 Win32Native.Color color2 = (Win32Native.Color)color;
1143 color2 = (Win32Native.Color)((
int)color2 << 4);
1149 private static ConsoleColor ColorAttributeToConsoleColor(Win32Native.Color c)
1151 if ((c & Win32Native.Color.BackgroundMask) != 0)
1153 c = (Win32Native.Color)((
int)c >> 4);
1161 [SecuritySafeCritical]
1166 Win32Native.CONSOLE_SCREEN_BUFFER_INFO bufferInfo = GetBufferInfo(throwOnNoConsole:
false, out succeeded);
1169 short attributes = _defaultColors;
1170 Win32Native.SetConsoleTextAttribute(ConsoleOutputHandle, attributes);
1188 public static void MoveBufferArea(
int sourceLeft,
int sourceTop,
int sourceWidth,
int sourceHeight,
int targetLeft,
int targetTop)
1211 [SecuritySafeCritical]
1212 public unsafe
static void MoveBufferArea(
int sourceLeft,
int sourceTop,
int sourceWidth,
int sourceHeight,
int targetLeft,
int targetTop,
char sourceChar,
ConsoleColor sourceForeColor,
ConsoleColor sourceBackColor)
1214 if (sourceForeColor < ConsoleColor.Black || sourceForeColor >
ConsoleColor.White)
1218 if (sourceBackColor < ConsoleColor.Black || sourceBackColor >
ConsoleColor.White)
1222 Win32Native.CONSOLE_SCREEN_BUFFER_INFO bufferInfo = GetBufferInfo();
1223 Win32Native.COORD dwSize = bufferInfo.dwSize;
1224 if (sourceLeft < 0 || sourceLeft > dwSize.X)
1228 if (sourceTop < 0 || sourceTop > dwSize.Y)
1232 if (sourceWidth < 0 || sourceWidth > dwSize.X - sourceLeft)
1236 if (sourceHeight < 0 || sourceTop > dwSize.Y - sourceHeight)
1240 if (targetLeft < 0 || targetLeft > dwSize.X)
1244 if (targetTop < 0 || targetTop > dwSize.Y)
1248 if (sourceWidth == 0 || sourceHeight == 0)
1253 Win32Native.CHAR_INFO[] array =
new Win32Native.CHAR_INFO[sourceWidth * sourceHeight];
1254 dwSize.X = (short)sourceWidth;
1255 dwSize.Y = (short)sourceHeight;
1256 Win32Native.COORD bufferCoord =
default(Win32Native.COORD);
1257 Win32Native.SMALL_RECT readRegion =
default(Win32Native.SMALL_RECT);
1258 readRegion.Left = (short)sourceLeft;
1259 readRegion.Right = (short)(sourceLeft + sourceWidth - 1);
1260 readRegion.Top = (short)sourceTop;
1261 readRegion.Bottom = (short)(sourceTop + sourceHeight - 1);
1262 Win32Native.CHAR_INFO[] array2 = array;
1264 fixed (Win32Native.CHAR_INFO* pBuffer = array2)
1266 flag = Win32Native.ReadConsoleOutput(ConsoleOutputHandle, pBuffer, dwSize, bufferCoord, ref readRegion);
1270 __Error.WinIOError();
1272 Win32Native.COORD cOORD =
default(Win32Native.COORD);
1273 cOORD.X = (short)sourceLeft;
1274 Win32Native.Color color = ConsoleColorToColorAttribute(sourceBackColor, isBackground:
true);
1275 color |= ConsoleColorToColorAttribute(sourceForeColor, isBackground:
false);
1276 short wColorAttribute = (short)color;
1277 for (
int i = sourceTop; i < sourceTop + sourceHeight; i++)
1280 if (!Win32Native.FillConsoleOutputCharacter(ConsoleOutputHandle, sourceChar, sourceWidth, cOORD, out
int pNumCharsWritten))
1282 __Error.WinIOError();
1284 if (!Win32Native.FillConsoleOutputAttribute(ConsoleOutputHandle, wColorAttribute, sourceWidth, cOORD, out pNumCharsWritten))
1286 __Error.WinIOError();
1289 Win32Native.SMALL_RECT writeRegion =
default(Win32Native.SMALL_RECT);
1290 writeRegion.Left = (short)targetLeft;
1291 writeRegion.Right = (short)(targetLeft + sourceWidth);
1292 writeRegion.Top = (short)targetTop;
1293 writeRegion.Bottom = (short)(targetTop + sourceHeight);
1295 fixed (Win32Native.CHAR_INFO* buffer = array2)
1297 flag = Win32Native.WriteConsoleOutput(ConsoleOutputHandle, buffer, dwSize, bufferCoord, ref writeRegion);
1302 private static Win32Native.CONSOLE_SCREEN_BUFFER_INFO GetBufferInfo()
1305 return GetBufferInfo(throwOnNoConsole:
true, out succeeded);
1308 [SecuritySafeCritical]
1309 private static Win32Native.CONSOLE_SCREEN_BUFFER_INFO GetBufferInfo(
bool throwOnNoConsole, out
bool succeeded)
1312 IntPtr consoleOutputHandle = ConsoleOutputHandle;
1313 if (consoleOutputHandle == Win32Native.INVALID_HANDLE_VALUE)
1315 if (!throwOnNoConsole)
1317 return default(Win32Native.CONSOLE_SCREEN_BUFFER_INFO);
1319 throw new IOException(Environment.GetResourceString(
"IO.IO_NoConsole"));
1321 if (!Win32Native.GetConsoleScreenBufferInfo(consoleOutputHandle, out Win32Native.CONSOLE_SCREEN_BUFFER_INFO lpConsoleScreenBufferInfo))
1323 bool consoleScreenBufferInfo = Win32Native.GetConsoleScreenBufferInfo(Win32Native.GetStdHandle(-12), out lpConsoleScreenBufferInfo);
1324 if (!consoleScreenBufferInfo)
1326 consoleScreenBufferInfo = Win32Native.GetConsoleScreenBufferInfo(Win32Native.GetStdHandle(-10), out lpConsoleScreenBufferInfo);
1328 if (!consoleScreenBufferInfo)
1331 if (lastWin32Error == 6 && !throwOnNoConsole)
1333 return default(Win32Native.CONSOLE_SCREEN_BUFFER_INFO);
1335 __Error.WinIOError(lastWin32Error,
null);
1338 if (!_haveReadDefaultColors)
1340 _defaultColors = (byte)(lpConsoleScreenBufferInfo.wAttributes & 0xFF);
1341 _haveReadDefaultColors =
true;
1344 return lpConsoleScreenBufferInfo;
1357 [SecuritySafeCritical]
1361 Win32Native.CONSOLE_SCREEN_BUFFER_INFO bufferInfo = GetBufferInfo();
1362 Win32Native.SMALL_RECT srWindow = bufferInfo.srWindow;
1363 if (width < srWindow.Right + 1 || width >= 32767)
1367 if (height < srWindow.Bottom + 1 || height >= 32767)
1371 Win32Native.COORD size =
default(Win32Native.COORD);
1372 size.X = (short)width;
1373 size.Y = (short)height;
1374 if (!Win32Native.SetConsoleScreenBufferSize(ConsoleOutputHandle, size))
1376 __Error.WinIOError();
1389 [SecuritySafeCritical]
1401 Win32Native.CONSOLE_SCREEN_BUFFER_INFO bufferInfo = GetBufferInfo();
1403 Win32Native.COORD size =
default(Win32Native.COORD);
1404 size.X = bufferInfo.dwSize.X;
1405 size.Y = bufferInfo.dwSize.Y;
1406 if (bufferInfo.dwSize.X < bufferInfo.srWindow.Left + width)
1408 if (bufferInfo.srWindow.Left >= 32767 - width)
1412 size.X = (short)(bufferInfo.srWindow.Left + width);
1415 if (bufferInfo.dwSize.Y < bufferInfo.srWindow.Top + height)
1417 if (bufferInfo.srWindow.Top >= 32767 - height)
1421 size.Y = (short)(bufferInfo.srWindow.Top + height);
1424 if (flag && !Win32Native.SetConsoleScreenBufferSize(ConsoleOutputHandle, size))
1426 __Error.WinIOError();
1428 Win32Native.SMALL_RECT srWindow = bufferInfo.srWindow;
1429 srWindow.Bottom = (short)(srWindow.Top + height - 1);
1430 srWindow.Right = (short)(srWindow.Left + width - 1);
1431 if (!Win32Native.SetConsoleWindowInfo(ConsoleOutputHandle, absolute:
true, &srWindow))
1436 Win32Native.SetConsoleScreenBufferSize(ConsoleOutputHandle, bufferInfo.dwSize);
1438 Win32Native.COORD largestConsoleWindowSize = Win32Native.GetLargestConsoleWindowSize(ConsoleOutputHandle);
1439 if (width > largestConsoleWindowSize.X)
1443 if (height > largestConsoleWindowSize.Y)
1447 __Error.WinIOError(lastWin32Error,
string.Empty);
1460 [SecuritySafeCritical]
1464 Win32Native.CONSOLE_SCREEN_BUFFER_INFO bufferInfo = GetBufferInfo();
1465 Win32Native.SMALL_RECT srWindow = bufferInfo.srWindow;
1466 int num = left + srWindow.Right - srWindow.Left + 1;
1467 if (left < 0 || num > bufferInfo.dwSize.X || num < 0)
1471 int num2 = top + srWindow.Bottom - srWindow.Top + 1;
1472 if (top < 0 || num2 > bufferInfo.dwSize.Y || num2 < 0)
1476 srWindow.Bottom -= (short)(srWindow.Top - top);
1477 srWindow.Right -= (short)(srWindow.Left - left);
1478 srWindow.Left = (short)left;
1479 srWindow.Top = (short)top;
1480 if (!Win32Native.SetConsoleWindowInfo(ConsoleOutputHandle, absolute:
true, &srWindow))
1482 __Error.WinIOError();
1495 [SecuritySafeCritical]
1498 if (left < 0 || left >= 32767)
1502 if (top < 0 || top >= 32767)
1507 IntPtr consoleOutputHandle = ConsoleOutputHandle;
1508 Win32Native.COORD cursorPosition =
default(Win32Native.COORD);
1509 cursorPosition.X = (short)left;
1510 cursorPosition.Y = (short)top;
1511 if (!Win32Native.SetConsoleCursorPosition(consoleOutputHandle, cursorPosition))
1514 Win32Native.CONSOLE_SCREEN_BUFFER_INFO bufferInfo = GetBufferInfo();
1515 if (left < 0 || left >= bufferInfo.dwSize.X)
1519 if (top < 0 || top >= bufferInfo.dwSize.Y)
1523 __Error.WinIOError(lastWin32Error,
string.Empty);
1529 [SuppressUnmanagedCodeSecurity]
1530 private static extern int GetTitleNative(StringHandleOnStack outTitle, out
int outTitleLength);
1538 return ReadKey(intercept:
false);
1542 private static bool IsAltKeyDown(Win32Native.InputRecord ir)
1544 return (ir.keyEvent.controlKeyState & 3) != 0;
1548 private static bool IsKeyDownEvent(Win32Native.InputRecord ir)
1550 if (ir.eventType == 1)
1552 return ir.keyEvent.keyDown;
1558 private static bool IsModKey(Win32Native.InputRecord ir)
1560 short virtualKeyCode = ir.keyEvent.virtualKeyCode;
1561 if ((virtualKeyCode < 16 || virtualKeyCode > 18) && virtualKeyCode != 20 && virtualKeyCode != 144)
1563 return virtualKeyCode == 145;
1572 [SecuritySafeCritical]
1576 int numEventsRead = -1;
1577 Win32Native.InputRecord buffer;
1578 lock (ReadKeySyncObject)
1580 if (_cachedInputRecord.eventType == 1)
1582 buffer = _cachedInputRecord;
1583 if (_cachedInputRecord.keyEvent.repeatCount == 0)
1585 _cachedInputRecord.eventType = -1;
1589 _cachedInputRecord.keyEvent.repeatCount--;
1596 if (!Win32Native.ReadConsoleInput(ConsoleInputHandle, out buffer, 1, out numEventsRead) || numEventsRead == 0)
1600 short virtualKeyCode = buffer.keyEvent.virtualKeyCode;
1601 if ((IsKeyDownEvent(buffer) || virtualKeyCode == 18) && (buffer.keyEvent.uChar != 0 || !IsModKey(buffer)))
1604 if (!IsAltKeyDown(buffer))
1608 if (consoleKey < ConsoleKey.NumPad0 || consoleKey >
ConsoleKey.NumPad9)
1628 if (buffer.keyEvent.repeatCount > 1)
1630 buffer.keyEvent.repeatCount--;
1631 _cachedInputRecord = buffer;
1635 ControlKeyState controlKeyState = (ControlKeyState)buffer.keyEvent.controlKeyState;
1636 bool shift = (controlKeyState & ControlKeyState.ShiftPressed) != (ControlKeyState)0;
1637 bool alt = (controlKeyState & (ControlKeyState.RightAltPressed | ControlKeyState.LeftAltPressed)) != (ControlKeyState)0;
1638 bool control = (controlKeyState & (ControlKeyState.RightCtrlPressed | ControlKeyState.LeftCtrlPressed)) != (ControlKeyState)0;
1642 Write(buffer.keyEvent.uChar);
1647 private static bool BreakEvent(
int controlType)
1649 if (controlType == 0 || controlType == 1)
1652 if (cancelCallbacks ==
null)
1657 ControlCDelegateData controlCDelegateData =
new ControlCDelegateData(controlKey, cancelCallbacks);
1663 TimeSpan timeout =
new TimeSpan(0, 0, 30);
1664 controlCDelegateData.CompletionEvent.WaitOne(timeout, exitContext:
false);
1665 if (!controlCDelegateData.DelegateStarted)
1669 controlCDelegateData.CompletionEvent.WaitOne();
1670 controlCDelegateData.CompletionEvent.Close();
1671 return controlCDelegateData.Cancel;
1676 private static void ControlCDelegate(
object data)
1678 ControlCDelegateData controlCDelegateData = (ControlCDelegateData)data;
1681 controlCDelegateData.DelegateStarted =
true;
1682 ConsoleCancelEventArgs consoleCancelEventArgs =
new ConsoleCancelEventArgs(controlCDelegateData.ControlKey);
1683 controlCDelegateData.CancelCallbacks(
null, consoleCancelEventArgs);
1684 controlCDelegateData.Cancel = consoleCancelEventArgs.Cancel;
1688 controlCDelegateData.CompletionEvent.Set();
1712 return GetStandardFile(-12,
FileAccess.Write, bufferSize);
1735 return GetStandardFile(-10,
FileAccess.Read, bufferSize);
1758 return GetStandardFile(-11,
FileAccess.Write, bufferSize);
1766 [SecuritySafeCritical]
1776 lock (InternalSyncObject)
1787 [SecuritySafeCritical]
1796 _isOutTextWriterRedirected =
true;
1798 lock (InternalSyncObject)
1809 [SecuritySafeCritical]
1813 if (newError ==
null)
1818 _isErrorTextWriterRedirected =
true;
1820 lock (InternalSyncObject)
1900 public static void WriteLine(
char[] buffer,
int index,
int count)
1949 [CLSCompliant(
false)]
1970 [CLSCompliant(
false)]
2021 public static void WriteLine(
string format,
object arg0,
object arg1)
2037 public static void WriteLine(
string format,
object arg0,
object arg1,
object arg2)
2043 [CLSCompliant(
false)]
2045 public static void WriteLine(
string format,
object arg0,
object arg1,
object arg2,
object arg3, __arglist)
2049 object[] array =
new object[num];
2054 for (
int i = 4; i < num; i++)
2070 public static void WriteLine(
string format, params
object[] arg)
2091 public static void Write(
string format,
object arg0)
2106 public static void Write(
string format,
object arg0,
object arg1)
2122 public static void Write(
string format,
object arg0,
object arg1,
object arg2)
2124 Out.
Write(format, arg0, arg1, arg2);
2128 [CLSCompliant(
false)]
2130 public static void Write(
string format,
object arg0,
object arg1,
object arg2,
object arg3, __arglist)
2134 object[] array =
new object[num];
2139 for (
int i = 4; i < num; i++)
2155 public static void Write(
string format, params
object[] arg)
2210 public static void Write(
char[] buffer,
int index,
int count)
2259 [CLSCompliant(
false)]
2280 [CLSCompliant(
false)]
Represents a character encoding.To browse the .NET Framework source code for this type,...
Exposes the user interface.
Represents the standard input, output, and error streams for console applications....
static string ReadLine()
Reads the next line of characters from the standard input stream.
static bool IsInputRedirected
Gets a value that indicates whether input has been redirected from the standard input stream.
static void Write(double value)
Writes the text representation of the specified double-precision floating-point value to the standard...
The exception that is thrown when a null reference (Nothing in Visual Basic) is passed to a method th...
static void ResetColor()
Sets the foreground and background console colors to their defaults.
Describes a set of security permissions applied to code. This class cannot be inherited.
static void Beep()
Plays the sound of a beep through the console speaker.
static void WriteLine(string format, object arg0, object arg1)
Writes the text representation of the specified objects, followed by the current line terminator,...
static void WriteLine(string value)
Writes the specified string value, followed by the current line terminator, to the standard output st...
static void MemoryBarrier()
Synchronizes memory access as follows: The processor executing the current thread cannot reorder inst...
static void WriteLine(string format, params object[] arg)
Writes the text representation of the specified array of objects, followed by the current line termin...
static bool QueueUserWorkItem(WaitCallback callBack, object state)
Queues a method for execution, and specifies an object containing data to be used by the method....
static TextWriter Out
Gets the standard output stream.
static new readonly StreamWriter Null
Provides a StreamWriter with no backing store that can be written to, but not read from.
static void Write(int value)
Writes the text representation of the specified 32-bit signed integer value to the standard output st...
static void WriteLine(ulong value)
Writes the text representation of the specified 64-bit unsigned integer value, followed by the curren...
static void WriteLine(double value)
Writes the text representation of the specified double-precision floating-point value,...
Ensures that all finalization code in derived classes is marked as critical.
int GetRemainingCount()
Returns the number of arguments remaining in the argument list.
static void WriteLine(int value)
Writes the text representation of the specified 32-bit signed integer value, followed by the current ...
static void Write(bool value)
Writes the text representation of the specified Boolean value to the standard output stream.
static new readonly StreamReader Null
A T:System.IO.StreamReader object around an empty stream.
The exception that is thrown when the value of an argument is outside the allowable range of values a...
static bool CursorVisible
Gets or sets a value indicating whether the cursor is visible.
UIPermissionWindow
Specifies the type of windows that code is allowed to use.
static void SetBufferSize(int width, int height)
Sets the height and width of the screen buffer area to the specified values.
static int CursorTop
Gets or sets the row position of the cursor within the buffer area.
Implements a T:System.IO.TextReader that reads characters from a byte stream in a particular encoding...
unsafe TypedReference GetNextArg()
Returns the next argument in a variable-length argument list.
static unsafe void SetWindowSize(int width, int height)
Sets the height and width of the console window to the specified values.
static void Write(string format, object arg0, object arg1, object arg2)
Writes the text representation of the specified objects to the standard output stream using the speci...
static void Clear()
Clears the console buffer and corresponding console window of display information.
static void WriteLine()
Writes the current line terminator to the standard output stream.
ConsoleColor
Specifies constants that define foreground and background colors for the console.
static int BufferHeight
Gets or sets the height of the buffer area.
static unsafe void MoveBufferArea(int sourceLeft, int sourceTop, int sourceWidth, int sourceHeight, int targetLeft, int targetTop, char sourceChar, ConsoleColor sourceForeColor, ConsoleColor sourceBackColor)
Copies a specified source area of the screen buffer to a specified destination area.
static Delegate Remove(Delegate source, Delegate value)
Removes the last occurrence of the invocation list of a delegate from the invocation list of another ...
static Delegate Combine(Delegate a, Delegate b)
Concatenates the invocation lists of two delegates.
static Encoding GetEncoding(int codepage)
Returns the encoding associated with the specified code page identifier.
static int Read()
Reads the next character from the standard input stream.
static void WriteLine(uint value)
Writes the text representation of the specified 32-bit unsigned integer value, followed by the curren...
Cer
Specifies a method's behavior when called within a constrained execution region.
static unsafe void SetWindowPosition(int left, int top)
Sets the position of the console window relative to the screen buffer.
Represents a variable-length argument list; that is, the parameters of a function that takes a variab...
static unsafe object ToObject(TypedReference value)
Converts the specified TypedReference to an Object.
static int WindowWidth
Gets or sets the width of the console window.
static int CursorSize
Gets or sets the height of the cursor within a character cell.
static void WriteLine(decimal value)
Writes the text representation of the specified T:System.Decimal value, followed by the current line ...
SecurityAction
Specifies the security actions that can be performed using declarative security.
Implements a T:System.IO.TextWriter for writing characters to a stream in a particular encoding....
static bool CapsLock
Gets a value indicating whether the CAPS LOCK keyboard toggle is turned on or turned off.
Provides information about, and means to manipulate, the current environment and platform....
Describes objects that contain both a managed pointer to a location and a runtime representation of t...
static void Write(char[] buffer, int index, int count)
Writes the specified subarray of Unicode characters to the standard output stream.
static readonly Stream Null
A Stream with no backing store.
static void WriteLine(char value)
Writes the specified Unicode character, followed by the current line terminator, value to the standar...
Represents a UTF-16 encoding of Unicode characters.
static void Write(string format, object arg0, object arg1)
Writes the text representation of the specified objects to the standard output stream using the speci...
static void WriteLine(string format, object arg0)
Writes the text representation of the specified object, followed by the current line terminator,...
static void SetIn(TextReader newIn)
Sets the P:System.Console.In property to the specified T:System.IO.TextReader object.
virtual int CodePage
When overridden in a derived class, gets the code page identifier of the current T:System....
virtual int Read()
Reads the next character from the text reader and advances the character position by one character.
static ConsoleColor ForegroundColor
Gets or sets the foreground color of the console.
static int CompareExchange(ref int location1, int value, int comparand)
Compares two 32-bit signed integers for equality and, if they are equal, replaces the first value.
static ConsoleCancelEventHandler CancelKeyPress
Occurs when the F:System.ConsoleModifiers.Control modifier key (Ctrl) and either the F:System....
ConsoleSpecialKey
Specifies combinations of modifier and console keys that can interrupt the current process.
static void Write(string format, params object[] arg)
Writes the text representation of the specified array of objects to the standard output stream using ...
static TextReader In
Gets the standard input stream.
The exception that is thrown when an I/O error occurs.
Represents a writer that can write a sequential series of characters. This class is abstract.
Controls the permissions related to user interfaces and the Clipboard. This class cannot be inherited...
static TextWriter Error
Gets the standard error output stream.
A platform-specific type that is used to represent a pointer or a handle.
Notifies one or more waiting threads that an event has occurred. This class cannot be inherited.
static void SetOut(TextWriter newOut)
Sets the P:System.Console.Out property to the specified T:System.IO.TextWriter object.
Represents a delegate, which is a data structure that refers to a static method or to a class instanc...
static void WriteLine(long value)
Writes the text representation of the specified 64-bit signed integer value, followed by the current ...
Provides a collection of methods for allocating unmanaged memory, copying unmanaged memory blocks,...
static Stream OpenStandardOutput(int bufferSize)
Acquires the standard output stream, which is set to a specified buffer size.
static Stream OpenStandardInput(int bufferSize)
Acquires the standard input stream, which is set to a specified buffer size.
MethodImplOptions
Defines the details of how a method is implemented.
static void WriteLine(string format, object arg0, object arg1, object arg2)
Writes the text representation of the specified objects, followed by the current line terminator,...
CharSet
Dictates which character set marshaled strings should use.
Describes the console key that was pressed, including the character represented by the console key an...
virtual void Flush()
Clears all buffers for the current writer and causes any buffered data to be written to the underlyin...
static void Write(object value)
Writes the text representation of the specified object to the standard output stream.
virtual bool AutoFlush
Gets or sets a value indicating whether the T:System.IO.StreamWriter will flush its buffer to the und...
static int WindowLeft
Gets or sets the leftmost position of the console window area relative to the screen buffer.
static int LargestWindowHeight
Gets the largest possible number of console window rows, based on the current font and screen resolut...
static void Write(string format, object arg0)
Writes the text representation of the specified object to the standard output stream using the specif...
The exception that is thrown when one of the arguments provided to a method is not valid.
void Demand()
Forces a T:System.Security.SecurityException at run time if all callers higher in the call stack have...
static void Write(char value)
Writes the specified Unicode character value to the standard output stream.
static void WriteLine(char[] buffer)
Writes the specified array of Unicode characters, followed by the current line terminator,...
static void WriteLine(char[] buffer, int index, int count)
Writes the specified subarray of Unicode characters, followed by the current line terminator,...
static void Write(ulong value)
Writes the text representation of the specified 64-bit unsigned integer value to the standard output ...
static void WriteLine(bool value)
Writes the text representation of the specified Boolean value, followed by the current line terminato...
static bool IsOutputRedirected
Gets a value that indicates whether output has been redirected from the standard output stream.
static int BufferWidth
Gets or sets the width of the buffer area.
FileAccess
Defines constants for read, write, or read/write access to a file.
static void Write(float value)
Writes the text representation of the specified single-precision floating-point value to the standard...
static int WindowHeight
Gets or sets the height of the console window area.
Represents a reader that can read a sequential series of characters.
static readonly IntPtr Zero
A read-only field that represents a pointer or handle that has been initialized to zero.
static void WriteLine(object value)
Writes the text representation of the specified object, followed by the current line terminator,...
static TextReader Synchronized(TextReader reader)
Creates a thread-safe wrapper around the specified TextReader.
static TextWriter Synchronized(TextWriter writer)
Creates a thread-safe wrapper around the specified TextWriter.
static Stream OpenStandardError(int bufferSize)
Acquires the standard error stream, which is set to a specified buffer size.
virtual void WriteLine()
Writes a line terminator to the text string or stream.
static ConsoleKeyInfo ReadKey(bool intercept)
Obtains the next character or function key pressed by the user. The pressed key is optionally display...
static string Title
Gets or sets the title to display in the console title bar.
static void SetCursorPosition(int left, int top)
Sets the position of the cursor.
The exception that is thrown when a method call is invalid for the object's current state.
static ConsoleColor BackgroundColor
Gets or sets the background color of the console.
Consistency
Specifies a reliability contract.
static int WindowTop
Gets or sets the top position of the console window area relative to the screen buffer.
static void Write(long value)
Writes the text representation of the specified 64-bit signed integer value to the standard output st...
ConsoleKey
Specifies the standard keys on a console.
delegate void WaitCallback(object state)
Represents a callback method to be executed by a thread pool thread.
static ConsoleKeyInfo ReadKey()
Obtains the next character or function key pressed by the user. The pressed key is displayed in the c...
static Encoding OutputEncoding
Gets or sets the encoding the console uses to write output.
static void Write(uint value)
Writes the text representation of the specified 32-bit unsigned integer value to the standard output ...
static void Write(decimal value)
Writes the text representation of the specified T:System.Decimal value to the standard output stream.
static int GetLastWin32Error()
Returns the error code returned by the last unmanaged function that was called using platform invoke ...
static Stream OpenStandardOutput()
Acquires the standard output stream.
SecurityPermissionFlag
Specifies access flags for the security permission object.
virtual void Write(char value)
Writes a character to the text string or stream.
static Stream OpenStandardError()
Acquires the standard error stream.
delegate void ConsoleCancelEventHandler(object sender, ConsoleCancelEventArgs e)
Represents the method that will handle the E:System.Console.CancelKeyPress event of a T:System....
static void WriteLine(float value)
Writes the text representation of the specified single-precision floating-point value,...
static bool KeyAvailable
Gets a value indicating whether a key press is available in the input stream.
static bool NumberLock
Gets a value indicating whether the NUM LOCK keyboard toggle is turned on or turned off.
Provides atomic operations for variables that are shared by multiple threads.
virtual string ReadLine()
Reads a line of characters from the text reader and returns the data as a string.
static int LargestWindowWidth
Gets the largest possible number of console window columns, based on the current font and screen reso...
static void MoveBufferArea(int sourceLeft, int sourceTop, int sourceWidth, int sourceHeight, int targetLeft, int targetTop)
Copies a specified source area of the screen buffer to a specified destination area.
static Stream OpenStandardInput()
Acquires the standard input stream.
static void Beep(int frequency, int duration)
Plays the sound of a beep of a specified frequency and duration through the console speaker.
static void Write(string value)
Writes the specified string value to the standard output stream.
static bool? TreatControlCAsInput
Gets or sets a value indicating whether the combination of the F:System.ConsoleModifiers....
static void SetError(TextWriter newError)
Sets the P:System.Console.Error property to the specified T:System.IO.TextWriter object.
static Encoding InputEncoding
Gets or sets the encoding the console uses to read input.
Provides a pool of threads that can be used to execute tasks, post work items, process asynchronous I...
static int CursorLeft
Gets or sets the column position of the cursor within the buffer area.
static void Write(char[] buffer)
Writes the specified array of Unicode characters to the standard output stream.
Provides a generic view of a sequence of bytes. This is an abstract class.To browse the ....
Creates and controls a thread, sets its priority, and gets its status.
static bool IsErrorRedirected
Gets a value that indicates whether the error output stream has been redirected from the standard err...