-
Notifications
You must be signed in to change notification settings - Fork 4.8k
/
ConsolePal.Windows.cs
1228 lines (1061 loc) · 54.5 KB
/
ConsolePal.Windows.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
namespace System
{
// Provides Windows-based support for System.Console.
internal static class ConsolePal
{
/// <summary>Hardcoded Encoding.Unicode.CodePage to avoid accessing Encoding.Unicode and forcing it into existence unnecessarily.</summary>
private const int UnicodeCodePage = 1200;
#if DEBUG
static ConsolePal() => Debug.Assert(UnicodeCodePage == Encoding.Unicode.CodePage);
#endif
private static IntPtr InvalidHandleValue => new IntPtr(-1);
/// <summary>Ensures that the console has been initialized for use.</summary>
internal static void EnsureConsoleInitialized()
{ }
private static bool IsWindows7()
{
// Version lies for all apps from the OS kick in starting with Windows 8 (6.2). They can
// also be added via appcompat (by the OS or the users) so this can only be used as a hint.
Version version = Environment.OSVersion.Version;
return version.Major == 6 && version.Minor == 1;
}
public static Stream OpenStandardInput() =>
GetStandardFile(
Interop.Kernel32.HandleTypes.STD_INPUT_HANDLE,
FileAccess.Read,
useFileAPIs: Console.InputEncoding.CodePage != UnicodeCodePage || Console.IsInputRedirected);
public static Stream OpenStandardOutput() =>
GetStandardFile(
Interop.Kernel32.HandleTypes.STD_OUTPUT_HANDLE,
FileAccess.Write,
useFileAPIs: Console.OutputEncoding.CodePage != UnicodeCodePage || Console.IsOutputRedirected);
public static Stream OpenStandardError() =>
GetStandardFile(
Interop.Kernel32.HandleTypes.STD_ERROR_HANDLE,
FileAccess.Write,
useFileAPIs: Console.OutputEncoding.CodePage != UnicodeCodePage || Console.IsErrorRedirected);
private static IntPtr InputHandle =>
Interop.Kernel32.GetStdHandle(Interop.Kernel32.HandleTypes.STD_INPUT_HANDLE);
private static IntPtr OutputHandle =>
Interop.Kernel32.GetStdHandle(Interop.Kernel32.HandleTypes.STD_OUTPUT_HANDLE);
private static IntPtr ErrorHandle =>
Interop.Kernel32.GetStdHandle(Interop.Kernel32.HandleTypes.STD_ERROR_HANDLE);
private static Stream GetStandardFile(int handleType, FileAccess access, bool useFileAPIs)
{
IntPtr handle = Interop.Kernel32.GetStdHandle(handleType);
// If someone launches a managed process via CreateProcess, stdout,
// stderr, & stdin could independently be set to INVALID_HANDLE_VALUE.
// Additionally they might use 0 as an invalid handle. We also need to
// ensure that if the handle is meant to be writable it actually is.
if (handle == IntPtr.Zero ||
handle == InvalidHandleValue ||
(access != FileAccess.Read && !ConsoleHandleIsWritable(handle)))
{
return Stream.Null;
}
return new WindowsConsoleStream(handle, access, useFileAPIs);
}
// Checks whether stdout or stderr are writable. Do NOT pass
// stdin here! The console handles are set to values like 3, 7,
// and 11 OR if you've been created via CreateProcess, possibly -1
// or 0. -1 is definitely invalid, while 0 is probably invalid.
// Also note each handle can independently be invalid or good.
// For Windows apps, the console handles are set to values like 3, 7,
// and 11 but are invalid handles - you may not write to them. However,
// you can still spawn a Windows app via CreateProcess and read stdout
// and stderr. So, we always need to check each handle independently for validity
// by trying to write or read to it, unless it is -1.
private static unsafe bool ConsoleHandleIsWritable(IntPtr outErrHandle)
{
// Windows apps may have non-null valid looking handle values for
// stdin, stdout and stderr, but they may not be readable or
// writable. Verify this by calling WriteFile in the
// appropriate modes. This must handle console-less Windows apps.
int bytesWritten;
byte junkByte = 0x41;
int r = Interop.Kernel32.WriteFile(outErrHandle, &junkByte, 0, out bytesWritten, IntPtr.Zero);
return r != 0; // In Win32 apps w/ no console, bResult should be 0 for failure.
}
public static Encoding InputEncoding
{
get { return EncodingHelper.GetSupportedConsoleEncoding((int)Interop.Kernel32.GetConsoleCP()); }
}
public static void SetConsoleInputEncoding(Encoding enc)
{
if (enc.CodePage != UnicodeCodePage)
{
if (!Interop.Kernel32.SetConsoleCP(enc.CodePage))
throw Win32Marshal.GetExceptionForWin32Error(Marshal.GetLastPInvokeError());
}
}
public static Encoding OutputEncoding
{
get { return EncodingHelper.GetSupportedConsoleEncoding((int)Interop.Kernel32.GetConsoleOutputCP()); }
}
public static void SetConsoleOutputEncoding(Encoding enc)
{
if (enc.CodePage != UnicodeCodePage)
{
if (!Interop.Kernel32.SetConsoleOutputCP(enc.CodePage))
throw Win32Marshal.GetExceptionForWin32Error(Marshal.GetLastPInvokeError());
}
}
/// <summary>Gets whether Console.In is targeting a terminal display.</summary>
public static bool IsInputRedirectedCore()
{
return IsHandleRedirected(InputHandle);
}
/// <summary>Gets whether Console.Out is targeting a terminal display.</summary>
public static bool IsOutputRedirectedCore()
{
return IsHandleRedirected(OutputHandle);
}
/// <summary>Gets whether Console.In is targeting a terminal display.</summary>
public static bool IsErrorRedirectedCore()
{
return IsHandleRedirected(ErrorHandle);
}
private static bool IsHandleRedirected(IntPtr handle)
{
// If handle is not to a character device, we must be redirected:
uint fileType = Interop.Kernel32.GetFileType(handle);
if ((fileType & Interop.Kernel32.FileTypes.FILE_TYPE_CHAR) != Interop.Kernel32.FileTypes.FILE_TYPE_CHAR)
return true;
// We are on a char device if GetConsoleMode succeeds and so we are not redirected.
return (!Interop.Kernel32.IsGetConsoleModeCallSuccessful(handle));
}
internal static TextReader GetOrCreateReader()
{
Stream inputStream = OpenStandardInput();
return SyncTextReader.GetSynchronizedTextReader(inputStream == Stream.Null ?
StreamReader.Null :
new StreamReader(
stream: inputStream,
encoding: new ConsoleEncoding(Console.InputEncoding),
detectEncodingFromByteOrderMarks: false,
bufferSize: Console.ReadBufferSize,
leaveOpen: true));
}
// Use this for blocking in Console.ReadKey, which needs to protect itself in case multiple threads call it simultaneously.
// Use a ReadKey-specific lock though, to allow other fields to be initialized on this type.
private static readonly object s_readKeySyncObject = new object();
// ReadLine & Read can't use this because they need to use ReadFile
// to be able to handle redirected input. We have to accept that
// we will lose repeated keystrokes when someone switches from
// calling ReadKey to calling Read or ReadLine. Those methods should
// ideally flush this cache as well.
private static Interop.InputRecord _cachedInputRecord;
// Skip non key events. Generally we want to surface only KeyDown event
// and suppress KeyUp event from the same Key press but there are cases
// where the assumption of KeyDown-KeyUp pairing for a given key press
// is invalid. For example in IME Unicode keyboard input, we often see
// only KeyUp until the key is released.
private static bool IsKeyDownEvent(Interop.InputRecord ir)
{
return (ir.eventType == Interop.KEY_EVENT && ir.keyEvent.keyDown != Interop.BOOL.FALSE);
}
private static bool IsModKey(Interop.InputRecord ir)
{
// We should also skip over Shift, Control, and Alt, as well as caps lock.
// Apparently we don't need to check for 0xA0 through 0xA5, which are keys like
// Left Control & Right Control. See the ConsoleKey enum for these values.
short keyCode = ir.keyEvent.virtualKeyCode;
return ((keyCode >= 0x10 && keyCode <= 0x12)
|| keyCode == 0x14 || keyCode == 0x90 || keyCode == 0x91);
}
[Flags]
internal enum ControlKeyState
{
RightAltPressed = 0x0001,
LeftAltPressed = 0x0002,
RightCtrlPressed = 0x0004,
LeftCtrlPressed = 0x0008,
ShiftPressed = 0x0010,
NumLockOn = 0x0020,
ScrollLockOn = 0x0040,
CapsLockOn = 0x0080,
EnhancedKey = 0x0100
}
// For tracking Alt+NumPad unicode key sequence. When you press Alt key down
// and press a numpad unicode decimal sequence and then release Alt key, the
// desired effect is to translate the sequence into one Unicode KeyPress.
// We need to keep track of the Alt+NumPad sequence and surface the final
// unicode char alone when the Alt key is released.
private static bool IsAltKeyDown(Interop.InputRecord ir)
{
return (((ControlKeyState)ir.keyEvent.controlKeyState)
& (ControlKeyState.LeftAltPressed | ControlKeyState.RightAltPressed)) != 0;
}
private const int NumberLockVKCode = 0x90;
private const int CapsLockVKCode = 0x14;
public static bool NumberLock
{
get
{
try
{
short s = Interop.User32.GetKeyState(NumberLockVKCode);
return (s & 1) == 1;
}
catch (Exception)
{
// Since we depend on an extension api-set here
// it is not guaranteed to work across the board.
// In case of exception we simply throw PNSE
throw new PlatformNotSupportedException();
}
}
}
public static bool CapsLock
{
get
{
try
{
short s = Interop.User32.GetKeyState(CapsLockVKCode);
return (s & 1) == 1;
}
catch (Exception)
{
// Since we depend on an extension api-set here
// it is not guaranteed to work across the board.
// In case of exception we simply throw PNSE
throw new PlatformNotSupportedException();
}
}
}
public static bool KeyAvailable
{
get
{
if (_cachedInputRecord.eventType == Interop.KEY_EVENT)
return true;
Interop.InputRecord ir = default;
int numEventsRead = 0;
while (true)
{
bool r = Interop.Kernel32.PeekConsoleInput(InputHandle, out ir, 1, out numEventsRead);
if (!r)
{
int errorCode = Marshal.GetLastPInvokeError();
if (errorCode == Interop.Errors.ERROR_INVALID_HANDLE)
throw new InvalidOperationException(SR.InvalidOperation_ConsoleKeyAvailableOnFile);
throw Win32Marshal.GetExceptionForWin32Error(errorCode, "stdin");
}
if (numEventsRead == 0)
return false;
// Skip non key-down && mod key events.
if (!IsKeyDownEvent(ir) || IsModKey(ir))
{
r = Interop.Kernel32.ReadConsoleInput(InputHandle, out ir, 1, out numEventsRead);
if (!r)
throw Win32Marshal.GetExceptionForWin32Error(Marshal.GetLastPInvokeError());
}
else
{
return true;
}
}
} // get
}
private const short AltVKCode = 0x12;
public static ConsoleKeyInfo ReadKey(bool intercept)
{
Interop.InputRecord ir;
int numEventsRead = -1;
bool r;
lock (s_readKeySyncObject)
{
if (_cachedInputRecord.eventType == Interop.KEY_EVENT)
{
// We had a previous keystroke with repeated characters.
ir = _cachedInputRecord;
if (_cachedInputRecord.keyEvent.repeatCount == 0)
_cachedInputRecord.eventType = -1;
else
{
_cachedInputRecord.keyEvent.repeatCount--;
}
// We will return one key from this method, so we decrement the
// repeatCount here, leaving the cachedInputRecord in the "queue".
}
else
{ // We did NOT have a previous keystroke with repeated characters:
while (true)
{
r = Interop.Kernel32.ReadConsoleInput(InputHandle, out ir, 1, out numEventsRead);
if (!r || numEventsRead == 0)
{
// This will fail when stdin is redirected from a file or pipe.
// We could theoretically call Console.Read here, but I
// think we might do some things incorrectly then.
throw new InvalidOperationException(SR.InvalidOperation_ConsoleReadKeyOnFile);
}
short keyCode = ir.keyEvent.virtualKeyCode;
// First check for non-keyboard events & discard them. Generally we tap into only KeyDown events and ignore the KeyUp events
// but it is possible that we are dealing with a Alt+NumPad unicode key sequence, the final unicode char is revealed only when
// the Alt key is released (i.e when the sequence is complete). To avoid noise, when the Alt key is down, we should eat up
// any intermediate key strokes (from NumPad) that collectively forms the Unicode character.
if (!IsKeyDownEvent(ir))
{
// REVIEW: Unicode IME input comes through as KeyUp event with no accompanying KeyDown.
if (keyCode != AltVKCode)
continue;
}
char ch = (char)ir.keyEvent.uChar;
// In a Alt+NumPad unicode sequence, when the alt key is released uChar will represent the final unicode character, we need to
// surface this. VirtualKeyCode for this event will be Alt from the Alt-Up key event. This is probably not the right code,
// especially when we don't expose ConsoleKey.Alt, so this will end up being the hex value (0x12). VK_PACKET comes very
// close to being useful and something that we could look into using for this purpose...
if (ch == 0)
{
// Skip mod keys.
if (IsModKey(ir))
continue;
}
// When Alt is down, it is possible that we are in the middle of a Alt+NumPad unicode sequence.
// Escape any intermediate NumPad keys whether NumLock is on or not (notepad behavior)
ConsoleKey key = (ConsoleKey)keyCode;
if (IsAltKeyDown(ir) && ((key >= ConsoleKey.NumPad0 && key <= ConsoleKey.NumPad9)
|| (key == ConsoleKey.Clear) || (key == ConsoleKey.Insert)
|| (key >= ConsoleKey.PageUp && key <= ConsoleKey.DownArrow)))
{
continue;
}
if (ir.keyEvent.repeatCount > 1)
{
ir.keyEvent.repeatCount--;
_cachedInputRecord = ir;
}
break;
}
} // we did NOT have a previous keystroke with repeated characters.
}
ControlKeyState state = (ControlKeyState)ir.keyEvent.controlKeyState;
bool shift = (state & ControlKeyState.ShiftPressed) != 0;
bool alt = (state & (ControlKeyState.LeftAltPressed | ControlKeyState.RightAltPressed)) != 0;
bool control = (state & (ControlKeyState.LeftCtrlPressed | ControlKeyState.RightCtrlPressed)) != 0;
ConsoleKeyInfo info = new ConsoleKeyInfo((char)ir.keyEvent.uChar, (ConsoleKey)ir.keyEvent.virtualKeyCode, shift, alt, control);
if (!intercept)
Console.Write(ir.keyEvent.uChar);
return info;
}
public static bool TreatControlCAsInput
{
get
{
IntPtr handle = InputHandle;
if (handle == InvalidHandleValue)
throw new IOException(SR.IO_NoConsole);
int mode = 0;
if (!Interop.Kernel32.GetConsoleMode(handle, out mode))
throw Win32Marshal.GetExceptionForWin32Error(Marshal.GetLastPInvokeError());
return (mode & Interop.Kernel32.ENABLE_PROCESSED_INPUT) == 0;
}
set
{
IntPtr handle = InputHandle;
if (handle == InvalidHandleValue)
throw new IOException(SR.IO_NoConsole);
int mode = 0;
if (!Interop.Kernel32.GetConsoleMode(handle, out mode))
throw Win32Marshal.GetExceptionForWin32Error(Marshal.GetLastPInvokeError());
if (value)
{
mode &= ~Interop.Kernel32.ENABLE_PROCESSED_INPUT;
}
else
{
mode |= Interop.Kernel32.ENABLE_PROCESSED_INPUT;
}
if (!Interop.Kernel32.SetConsoleMode(handle, mode))
throw Win32Marshal.GetExceptionForWin32Error(Marshal.GetLastPInvokeError());
}
}
// For ResetColor
private static volatile bool _haveReadDefaultColors;
private static volatile byte _defaultColors;
public static ConsoleColor BackgroundColor
{
get
{
bool succeeded;
Interop.Kernel32.CONSOLE_SCREEN_BUFFER_INFO csbi = GetBufferInfo(false, out succeeded);
return succeeded ?
ColorAttributeToConsoleColor((Interop.Kernel32.Color)csbi.wAttributes & Interop.Kernel32.Color.BackgroundMask) :
ConsoleColor.Black; // for code that may be used from Windows app w/ no console
}
set
{
Interop.Kernel32.Color c = ConsoleColorToColorAttribute(value, true);
bool succeeded;
Interop.Kernel32.CONSOLE_SCREEN_BUFFER_INFO csbi = GetBufferInfo(false, out succeeded);
// For code that may be used from Windows app w/ no console
if (!succeeded)
return;
Debug.Assert(_haveReadDefaultColors, "Setting the background color before we've read the default foreground color!");
short attrs = csbi.wAttributes;
attrs &= ~((short)Interop.Kernel32.Color.BackgroundMask);
// C#'s bitwise-or sign-extends to 32 bits.
attrs = (short)(((uint)(ushort)attrs) | ((uint)(ushort)c));
// Ignore errors here - there are some scenarios for running code that wants
// to print in colors to the console in a Windows application.
Interop.Kernel32.SetConsoleTextAttribute(OutputHandle, attrs);
}
}
public static ConsoleColor ForegroundColor
{
get
{
bool succeeded;
Interop.Kernel32.CONSOLE_SCREEN_BUFFER_INFO csbi = GetBufferInfo(false, out succeeded);
// For code that may be used from Windows app w/ no console
return succeeded ?
ColorAttributeToConsoleColor((Interop.Kernel32.Color)csbi.wAttributes & Interop.Kernel32.Color.ForegroundMask) :
ConsoleColor.Gray;
}
set
{
Interop.Kernel32.Color c = ConsoleColorToColorAttribute(value, false);
bool succeeded;
Interop.Kernel32.CONSOLE_SCREEN_BUFFER_INFO csbi = GetBufferInfo(false, out succeeded);
// For code that may be used from Windows app w/ no console
if (!succeeded)
return;
Debug.Assert(_haveReadDefaultColors, "Setting the foreground color before we've read the default foreground color!");
short attrs = csbi.wAttributes;
attrs &= ~((short)Interop.Kernel32.Color.ForegroundMask);
// C#'s bitwise-or sign-extends to 32 bits.
attrs = (short)(((uint)(ushort)attrs) | ((uint)(ushort)c));
// Ignore errors here - there are some scenarios for running code that wants
// to print in colors to the console in a Windows application.
Interop.Kernel32.SetConsoleTextAttribute(OutputHandle, attrs);
}
}
public static void ResetColor()
{
if (!_haveReadDefaultColors) // avoid the costs of GetBufferInfo if we already know we checked it
{
bool succeeded;
GetBufferInfo(false, out succeeded);
if (!succeeded)
return; // For code that may be used from Windows app w/ no console
Debug.Assert(_haveReadDefaultColors, "Resetting color before we've read the default foreground color!");
}
// Ignore errors here - there are some scenarios for running code that wants
// to print in colors to the console in a Windows application.
Interop.Kernel32.SetConsoleTextAttribute(OutputHandle, (short)(ushort)_defaultColors);
}
public static int CursorSize
{
get
{
Interop.Kernel32.CONSOLE_CURSOR_INFO cci;
if (!Interop.Kernel32.GetConsoleCursorInfo(OutputHandle, out cci))
throw Win32Marshal.GetExceptionForWin32Error(Marshal.GetLastPInvokeError());
return cci.dwSize;
}
set
{
// Value should be a percentage from [1, 100].
if (value < 1 || value > 100)
throw new ArgumentOutOfRangeException(nameof(value), value, SR.ArgumentOutOfRange_CursorSize);
Interop.Kernel32.CONSOLE_CURSOR_INFO cci;
if (!Interop.Kernel32.GetConsoleCursorInfo(OutputHandle, out cci))
throw Win32Marshal.GetExceptionForWin32Error(Marshal.GetLastPInvokeError());
cci.dwSize = value;
if (!Interop.Kernel32.SetConsoleCursorInfo(OutputHandle, ref cci))
throw Win32Marshal.GetExceptionForWin32Error(Marshal.GetLastPInvokeError());
}
}
public static bool CursorVisible
{
get
{
Interop.Kernel32.CONSOLE_CURSOR_INFO cci;
if (!Interop.Kernel32.GetConsoleCursorInfo(OutputHandle, out cci))
throw Win32Marshal.GetExceptionForWin32Error(Marshal.GetLastPInvokeError());
return cci.bVisible != Interop.BOOL.FALSE;
}
set
{
Interop.Kernel32.CONSOLE_CURSOR_INFO cci;
if (!Interop.Kernel32.GetConsoleCursorInfo(OutputHandle, out cci))
throw Win32Marshal.GetExceptionForWin32Error(Marshal.GetLastPInvokeError());
cci.bVisible = value ? Interop.BOOL.TRUE : Interop.BOOL.FALSE;
if (!Interop.Kernel32.SetConsoleCursorInfo(OutputHandle, ref cci))
throw Win32Marshal.GetExceptionForWin32Error(Marshal.GetLastPInvokeError());
}
}
public static (int Left, int Top) GetCursorPosition()
{
Interop.Kernel32.CONSOLE_SCREEN_BUFFER_INFO csbi = GetBufferInfo();
return (csbi.dwCursorPosition.X, csbi.dwCursorPosition.Y);
}
public static unsafe string Title
{
get
{
ValueStringBuilder builder = new ValueStringBuilder(stackalloc char[256]);
while (true)
{
uint result = Interop.Errors.ERROR_SUCCESS;
fixed (char* c = builder)
{
result = Interop.Kernel32.GetConsoleTitleW(c, (uint)builder.Capacity);
}
// The documentation asserts that the console's title is stored in a shared 64KB buffer.
// The magic number that used to exist here (24500) is likely related to that.
// A full UNICODE_STRING is 32K chars...
Debug.Assert(result <= short.MaxValue, "shouldn't be possible to grow beyond UNICODE_STRING size");
if (result == 0)
{
int error = Marshal.GetLastPInvokeError();
switch (error)
{
case Interop.Errors.ERROR_INSUFFICIENT_BUFFER:
// Typically this API truncates but there was a bug in RS2 so we'll make an attempt to handle
builder.EnsureCapacity(builder.Capacity * 2);
continue;
case Interop.Errors.ERROR_SUCCESS:
// The title is empty.
break;
default:
throw Win32Marshal.GetExceptionForWin32Error(error, string.Empty);
}
}
else if (result >= builder.Capacity - 1 || (IsWindows7() && result >= builder.Capacity / sizeof(char) - 1))
{
// Our buffer was full. As this API truncates we need to increase our size and reattempt.
// Note that Windows 7 copies count of bytes into the output buffer but returns count of chars
// and as such our buffer is only "half" its actual size.
//
// (If we're Windows 10 with a version lie to 7 this will be inefficient so we'll want to remove
// this workaround when we no longer support Windows 7)
builder.EnsureCapacity(builder.Capacity * 2);
continue;
}
builder.Length = (int)result;
break;
}
return builder.ToString();
}
set
{
if (!Interop.Kernel32.SetConsoleTitle(value))
throw Win32Marshal.GetExceptionForWin32Error(Marshal.GetLastPInvokeError());
}
}
public static void Beep()
{
const int BeepFrequencyInHz = 800;
const int BeepDurationInMs = 200;
Interop.Kernel32.Beep(BeepFrequencyInHz, BeepDurationInMs);
}
public static void Beep(int frequency, int duration)
{
const int MinBeepFrequency = 37;
const int MaxBeepFrequency = 32767;
if (frequency < MinBeepFrequency || frequency > MaxBeepFrequency)
throw new ArgumentOutOfRangeException(nameof(frequency), frequency, SR.Format(SR.ArgumentOutOfRange_BeepFrequency, MinBeepFrequency, MaxBeepFrequency));
if (duration <= 0)
throw new ArgumentOutOfRangeException(nameof(duration), duration, SR.ArgumentOutOfRange_NeedPosNum);
Interop.Kernel32.Beep(frequency, duration);
}
public static unsafe void MoveBufferArea(int sourceLeft, int sourceTop,
int sourceWidth, int sourceHeight, int targetLeft, int targetTop,
char sourceChar, ConsoleColor sourceForeColor,
ConsoleColor sourceBackColor)
{
if (sourceForeColor < ConsoleColor.Black || sourceForeColor > ConsoleColor.White)
throw new ArgumentException(SR.Arg_InvalidConsoleColor, nameof(sourceForeColor));
if (sourceBackColor < ConsoleColor.Black || sourceBackColor > ConsoleColor.White)
throw new ArgumentException(SR.Arg_InvalidConsoleColor, nameof(sourceBackColor));
Interop.Kernel32.CONSOLE_SCREEN_BUFFER_INFO csbi = GetBufferInfo();
Interop.Kernel32.COORD bufferSize = csbi.dwSize;
if (sourceLeft < 0 || sourceLeft > bufferSize.X)
throw new ArgumentOutOfRangeException(nameof(sourceLeft), sourceLeft, SR.ArgumentOutOfRange_ConsoleBufferBoundaries);
if (sourceTop < 0 || sourceTop > bufferSize.Y)
throw new ArgumentOutOfRangeException(nameof(sourceTop), sourceTop, SR.ArgumentOutOfRange_ConsoleBufferBoundaries);
if (sourceWidth < 0 || sourceWidth > bufferSize.X - sourceLeft)
throw new ArgumentOutOfRangeException(nameof(sourceWidth), sourceWidth, SR.ArgumentOutOfRange_ConsoleBufferBoundaries);
if (sourceHeight < 0 || sourceTop > bufferSize.Y - sourceHeight)
throw new ArgumentOutOfRangeException(nameof(sourceHeight), sourceHeight, SR.ArgumentOutOfRange_ConsoleBufferBoundaries);
// Note: if the target range is partially in and partially out
// of the buffer, then we let the OS clip it for us.
if (targetLeft < 0 || targetLeft > bufferSize.X)
throw new ArgumentOutOfRangeException(nameof(targetLeft), targetLeft, SR.ArgumentOutOfRange_ConsoleBufferBoundaries);
if (targetTop < 0 || targetTop > bufferSize.Y)
throw new ArgumentOutOfRangeException(nameof(targetTop), targetTop, SR.ArgumentOutOfRange_ConsoleBufferBoundaries);
// If we're not doing any work, bail out now (Windows will return
// an error otherwise)
if (sourceWidth == 0 || sourceHeight == 0)
return;
// Read data from the original location, blank it out, then write
// it to the new location. This will handle overlapping source and
// destination regions correctly.
// Read the old data
Interop.Kernel32.CHAR_INFO[] data = new Interop.Kernel32.CHAR_INFO[sourceWidth * sourceHeight];
bufferSize.X = (short)sourceWidth;
bufferSize.Y = (short)sourceHeight;
Interop.Kernel32.COORD bufferCoord = default;
Interop.Kernel32.SMALL_RECT readRegion = default;
readRegion.Left = (short)sourceLeft;
readRegion.Right = (short)(sourceLeft + sourceWidth - 1);
readRegion.Top = (short)sourceTop;
readRegion.Bottom = (short)(sourceTop + sourceHeight - 1);
bool r;
fixed (Interop.Kernel32.CHAR_INFO* pCharInfo = data)
r = Interop.Kernel32.ReadConsoleOutput(OutputHandle, pCharInfo, bufferSize, bufferCoord, ref readRegion);
if (!r)
throw Win32Marshal.GetExceptionForWin32Error(Marshal.GetLastPInvokeError());
// Overwrite old section
Interop.Kernel32.COORD writeCoord = default;
writeCoord.X = (short)sourceLeft;
Interop.Kernel32.Color c = ConsoleColorToColorAttribute(sourceBackColor, true);
c |= ConsoleColorToColorAttribute(sourceForeColor, false);
short attr = (short)c;
int numWritten;
for (int i = sourceTop; i < sourceTop + sourceHeight; i++)
{
writeCoord.Y = (short)i;
r = Interop.Kernel32.FillConsoleOutputCharacter(OutputHandle, sourceChar, sourceWidth, writeCoord, out numWritten);
Debug.Assert(numWritten == sourceWidth, "FillConsoleOutputCharacter wrote the wrong number of chars!");
if (!r)
throw Win32Marshal.GetExceptionForWin32Error(Marshal.GetLastPInvokeError());
r = Interop.Kernel32.FillConsoleOutputAttribute(OutputHandle, attr, sourceWidth, writeCoord, out numWritten);
if (!r)
throw Win32Marshal.GetExceptionForWin32Error(Marshal.GetLastPInvokeError());
}
// Write text to new location
Interop.Kernel32.SMALL_RECT writeRegion = default;
writeRegion.Left = (short)targetLeft;
writeRegion.Right = (short)(targetLeft + sourceWidth);
writeRegion.Top = (short)targetTop;
writeRegion.Bottom = (short)(targetTop + sourceHeight);
fixed (Interop.Kernel32.CHAR_INFO* pCharInfo = data)
Interop.Kernel32.WriteConsoleOutput(OutputHandle, pCharInfo, bufferSize, bufferCoord, ref writeRegion);
}
public static void Clear()
{
Interop.Kernel32.COORD coordScreen = default;
Interop.Kernel32.CONSOLE_SCREEN_BUFFER_INFO csbi;
bool success;
int conSize;
IntPtr hConsole = OutputHandle;
if (hConsole == InvalidHandleValue)
throw new IOException(SR.IO_NoConsole);
// get the number of character cells in the current buffer
// Go through my helper method for fetching a screen buffer info
// to correctly handle default console colors.
csbi = GetBufferInfo();
conSize = csbi.dwSize.X * csbi.dwSize.Y;
// fill the entire screen with blanks
int numCellsWritten = 0;
success = Interop.Kernel32.FillConsoleOutputCharacter(hConsole, ' ',
conSize, coordScreen, out numCellsWritten);
if (!success)
throw Win32Marshal.GetExceptionForWin32Error(Marshal.GetLastPInvokeError());
// now set the buffer's attributes accordingly
numCellsWritten = 0;
success = Interop.Kernel32.FillConsoleOutputAttribute(hConsole, csbi.wAttributes,
conSize, coordScreen, out numCellsWritten);
if (!success)
throw Win32Marshal.GetExceptionForWin32Error(Marshal.GetLastPInvokeError());
// put the cursor at (0, 0)
success = Interop.Kernel32.SetConsoleCursorPosition(hConsole, coordScreen);
if (!success)
throw Win32Marshal.GetExceptionForWin32Error(Marshal.GetLastPInvokeError());
}
public static void SetCursorPosition(int left, int top)
{
IntPtr hConsole = OutputHandle;
Interop.Kernel32.COORD coords = default;
coords.X = (short)left;
coords.Y = (short)top;
if (!Interop.Kernel32.SetConsoleCursorPosition(hConsole, coords))
{
// Give a nice error message for out of range sizes
int errorCode = Marshal.GetLastPInvokeError();
Interop.Kernel32.CONSOLE_SCREEN_BUFFER_INFO csbi = GetBufferInfo();
if (left >= csbi.dwSize.X)
throw new ArgumentOutOfRangeException(nameof(left), left, SR.ArgumentOutOfRange_ConsoleBufferBoundaries);
if (top >= csbi.dwSize.Y)
throw new ArgumentOutOfRangeException(nameof(top), top, SR.ArgumentOutOfRange_ConsoleBufferBoundaries);
throw Win32Marshal.GetExceptionForWin32Error(errorCode);
}
}
public static int BufferWidth
{
get
{
Interop.Kernel32.CONSOLE_SCREEN_BUFFER_INFO csbi = GetBufferInfo();
return csbi.dwSize.X;
}
set
{
SetBufferSize(value, BufferHeight);
}
}
public static int BufferHeight
{
get
{
Interop.Kernel32.CONSOLE_SCREEN_BUFFER_INFO csbi = GetBufferInfo();
return csbi.dwSize.Y;
}
set
{
SetBufferSize(BufferWidth, value);
}
}
public static void SetBufferSize(int width, int height)
{
// Ensure the new size is not smaller than the console window
Interop.Kernel32.CONSOLE_SCREEN_BUFFER_INFO csbi = GetBufferInfo();
Interop.Kernel32.SMALL_RECT srWindow = csbi.srWindow;
if (width < srWindow.Right + 1 || width >= short.MaxValue)
throw new ArgumentOutOfRangeException(nameof(width), width, SR.ArgumentOutOfRange_ConsoleBufferLessThanWindowSize);
if (height < srWindow.Bottom + 1 || height >= short.MaxValue)
throw new ArgumentOutOfRangeException(nameof(height), height, SR.ArgumentOutOfRange_ConsoleBufferLessThanWindowSize);
Interop.Kernel32.COORD size = default;
size.X = (short)width;
size.Y = (short)height;
if (!Interop.Kernel32.SetConsoleScreenBufferSize(OutputHandle, size))
{
throw Win32Marshal.GetExceptionForWin32Error(Marshal.GetLastPInvokeError());
}
}
public static int LargestWindowWidth
{
get
{
// Note this varies based on current screen resolution and
// current console font. Do not cache this value.
Interop.Kernel32.COORD bounds = Interop.Kernel32.GetLargestConsoleWindowSize(OutputHandle);
return bounds.X;
}
}
public static int LargestWindowHeight
{
get
{
// Note this varies based on current screen resolution and
// current console font. Do not cache this value.
Interop.Kernel32.COORD bounds = Interop.Kernel32.GetLargestConsoleWindowSize(OutputHandle);
return bounds.Y;
}
}
public static int WindowLeft
{
get
{
Interop.Kernel32.CONSOLE_SCREEN_BUFFER_INFO csbi = GetBufferInfo();
return csbi.srWindow.Left;
}
set
{
SetWindowPosition(value, WindowTop);
}
}
public static int WindowTop
{
get
{
Interop.Kernel32.CONSOLE_SCREEN_BUFFER_INFO csbi = GetBufferInfo();
return csbi.srWindow.Top;
}
set
{
SetWindowPosition(WindowLeft, value);
}
}
public static int WindowWidth
{
get
{
Interop.Kernel32.CONSOLE_SCREEN_BUFFER_INFO csbi = GetBufferInfo();
return csbi.srWindow.Right - csbi.srWindow.Left + 1;
}
set
{
SetWindowSize(value, WindowHeight);
}
}
public static int WindowHeight
{
get
{
Interop.Kernel32.CONSOLE_SCREEN_BUFFER_INFO csbi = GetBufferInfo();
return csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
}
set
{
SetWindowSize(WindowWidth, value);
}
}
public static unsafe void SetWindowPosition(int left, int top)
{
// Get the size of the current console window
Interop.Kernel32.CONSOLE_SCREEN_BUFFER_INFO csbi = GetBufferInfo();
Interop.Kernel32.SMALL_RECT srWindow = csbi.srWindow;
// Check for arithmetic underflows & overflows.
int newRight = left + srWindow.Right - srWindow.Left;
if (left < 0 || newRight > csbi.dwSize.X - 1 || newRight < left)
throw new ArgumentOutOfRangeException(nameof(left), left, SR.ArgumentOutOfRange_ConsoleWindowPos);
int newBottom = top + srWindow.Bottom - srWindow.Top;
if (top < 0 || newBottom > csbi.dwSize.Y - 1 || newBottom < top)
throw new ArgumentOutOfRangeException(nameof(top), top, SR.ArgumentOutOfRange_ConsoleWindowPos);
// Preserve the size, but move the position.
srWindow.Bottom = (short)newBottom;
srWindow.Right = (short)newRight;
srWindow.Left = (short)left;
srWindow.Top = (short)top;
bool r = Interop.Kernel32.SetConsoleWindowInfo(OutputHandle, true, &srWindow);
if (!r)
throw Win32Marshal.GetExceptionForWin32Error(Marshal.GetLastPInvokeError());
}
public static unsafe void SetWindowSize(int width, int height)
{
if (width <= 0)
throw new ArgumentOutOfRangeException(nameof(width), width, SR.ArgumentOutOfRange_NeedPosNum);
if (height <= 0)
throw new ArgumentOutOfRangeException(nameof(height), height, SR.ArgumentOutOfRange_NeedPosNum);
// Get the position of the current console window
Interop.Kernel32.CONSOLE_SCREEN_BUFFER_INFO csbi = GetBufferInfo();
// If the buffer is smaller than this new window size, resize the
// buffer to be large enough. Include window position.
bool resizeBuffer = false;
Interop.Kernel32.COORD size = default;
size.X = csbi.dwSize.X;
size.Y = csbi.dwSize.Y;
if (csbi.dwSize.X < csbi.srWindow.Left + width)
{
if (csbi.srWindow.Left >= short.MaxValue - width)
throw new ArgumentOutOfRangeException(nameof(width), SR.Format(SR.ArgumentOutOfRange_ConsoleWindowBufferSize, short.MaxValue - width));
size.X = (short)(csbi.srWindow.Left + width);
resizeBuffer = true;
}
if (csbi.dwSize.Y < csbi.srWindow.Top + height)
{
if (csbi.srWindow.Top >= short.MaxValue - height)
throw new ArgumentOutOfRangeException(nameof(height), SR.Format(SR.ArgumentOutOfRange_ConsoleWindowBufferSize, short.MaxValue - height));
size.Y = (short)(csbi.srWindow.Top + height);
resizeBuffer = true;
}
if (resizeBuffer)
{
if (!Interop.Kernel32.SetConsoleScreenBufferSize(OutputHandle, size))
throw Win32Marshal.GetExceptionForWin32Error(Marshal.GetLastPInvokeError());
}
Interop.Kernel32.SMALL_RECT srWindow = csbi.srWindow;
// Preserve the position, but change the size.
srWindow.Bottom = (short)(srWindow.Top + height - 1);
srWindow.Right = (short)(srWindow.Left + width - 1);
if (!Interop.Kernel32.SetConsoleWindowInfo(OutputHandle, true, &srWindow))
{
int errorCode = Marshal.GetLastPInvokeError();