forked from PowerShell/PowerShell
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathConsoleHostRawUserInterface.cs
More file actions
1863 lines (1627 loc) · 66 KB
/
Copy pathConsoleHostRawUserInterface.cs
File metadata and controls
1863 lines (1627 loc) · 66 KB
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
#if !UNIX
/********************************************************************++
Copyright (c) Microsoft Corporation. All rights reserved.
--********************************************************************/
using System;
using System.Management.Automation;
using System.Management.Automation.Internal;
using System.Management.Automation.Host;
using System.ComponentModel;
using System.Globalization;
using System.Security.Principal;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Dbg = System.Management.Automation.Diagnostics;
using ConsoleHandle = Microsoft.Win32.SafeHandles.SafeFileHandle;
using WORD = System.UInt16;
using DWORD = System.UInt32;
namespace Microsoft.PowerShell
{
/// <summary>
///
/// implementation of RawConsole for powershell.exe
///
/// </summary>
internal sealed
class ConsoleHostRawUserInterface : System.Management.Automation.Host.PSHostRawUserInterface
{
/// <summary>
///
/// </summary>
/// <exception cref="HostException">
///
/// If obtaining the buffer's foreground and background color failed
///
/// </exception>
internal
ConsoleHostRawUserInterface(ConsoleHostUserInterface mshConsole) : base()
{
defaultForeground = ForegroundColor;
defaultBackground = BackgroundColor;
parent = mshConsole;
// cacheKeyEvent is a value type and initialized automatically
// add "Administrator: " prefix into the window title, but don't wait for it to finish
// (we may load resources which can take some time)
Task.Run(() =>
{
WindowsIdentity identity = WindowsIdentity.GetCurrent();
WindowsPrincipal principal = new WindowsPrincipal(identity);
if (principal.IsInRole(WindowsBuiltInRole.Administrator))
{
string prefix = ConsoleHostRawUserInterfaceStrings.WindowTitleElevatedPrefix;
// check using Regex if the window already has Administrator: prefix
// (i.e. from the parent console process)
string titlePattern = ConsoleHostRawUserInterfaceStrings.WindowTitleTemplate;
titlePattern = Regex.Escape(titlePattern)
.Replace(@"\{1}", ".*")
.Replace(@"\{0}", Regex.Escape(prefix));
if (!Regex.IsMatch(this.WindowTitle, titlePattern))
{
this.WindowTitle = StringUtil.Format(ConsoleHostRawUserInterfaceStrings.WindowTitleTemplate,
prefix,
this.WindowTitle);
}
}
});
}
/// <summary>
///
/// See base class
///
/// </summary>
/// <value></value>
/// <exception cref="ArgumentException">
///
/// If set to an invalid ConsoleColor
///
/// </exception>
/// <exception cref="HostException">
///
/// If obtaining information about the buffer failed
/// OR
/// Win32's SetConsoleTextAttribute
///
/// </exception>
public override
ConsoleColor
ForegroundColor
{
get
{
ConsoleControl.CONSOLE_SCREEN_BUFFER_INFO bufferInfo;
GetBufferInfo(out bufferInfo);
ConsoleColor foreground;
ConsoleColor unused;
ConsoleControl.WORDToColor(bufferInfo.Attributes, out foreground, out unused);
return foreground;
}
set
{
if (ConsoleControl.IsConsoleColor(value))
{
ConsoleControl.CONSOLE_SCREEN_BUFFER_INFO bufferInfo;
ConsoleHandle handle = GetBufferInfo(out bufferInfo);
// mask in the foreground from the current color.
short a = (short)bufferInfo.Attributes;
a &= (short)~0x0f;
a = (short)((ushort)a | (ushort)value);
ConsoleControl.SetConsoleTextAttribute(handle, (WORD)a);
}
else
{
throw PSTraceSource.NewArgumentException("value", ConsoleHostRawUserInterfaceStrings.InvalidConsoleColorError);
}
}
}
/// <summary>
///
/// See base class
///
/// </summary>
/// <value></value>
/// <exception cref="ArgumentException">
///
/// If set to an invalid ConsoleColor
///
/// </exception>
/// <exception cref="HostException">
///
/// If obtaining information about the buffer failed
/// OR
/// Win32's SetConsoleTextAttribute
///
/// </exception>
public override
ConsoleColor
BackgroundColor
{
get
{
ConsoleControl.CONSOLE_SCREEN_BUFFER_INFO bufferInfo;
GetBufferInfo(out bufferInfo);
ConsoleColor background;
ConsoleColor unused;
ConsoleControl.WORDToColor(bufferInfo.Attributes, out unused, out background);
return background;
}
set
{
if (ConsoleControl.IsConsoleColor(value))
{
ConsoleControl.CONSOLE_SCREEN_BUFFER_INFO bufferInfo;
ConsoleHandle handle = GetBufferInfo(out bufferInfo);
// mask in the background from the current color.
short a = (short)bufferInfo.Attributes;
a &= (short)~0xf0;
a = (short)((ushort)a | (ushort)((uint)value << 4));
ConsoleControl.SetConsoleTextAttribute(handle, (WORD)a);
}
else
{
throw PSTraceSource.NewArgumentException("value", ConsoleHostRawUserInterfaceStrings.InvalidConsoleColorError);
}
}
}
/// <summary>
///
/// See base class
///
/// </summary>
/// <value></value>
/// <exception cref="ArgumentOutOfRangeException">
///
/// If set to outside of the buffer
///
/// </exception>
/// <exception cref="HostException">
///
/// If obtaining information about the buffer failed
/// OR
/// Win32's SetConsoleCursorPosition failed
///
/// </exception>
public override
Coordinates
CursorPosition
{
get
{
ConsoleControl.CONSOLE_SCREEN_BUFFER_INFO bufferInfo;
GetBufferInfo(out bufferInfo);
Coordinates c = new Coordinates(bufferInfo.CursorPosition.X, bufferInfo.CursorPosition.Y);
return c;
}
set
{
// cursor position can't be outside the buffer area
ConsoleControl.CONSOLE_SCREEN_BUFFER_INFO bufferInfo;
ConsoleHandle handle = GetBufferInfo(out bufferInfo);
CheckCoordinateWithinBuffer(ref value, ref bufferInfo, "value");
ConsoleControl.SetConsoleCursorPosition(handle, value);
}
}
/// <summary>
///
/// See base class
///
/// </summary>
/// <value>
///
/// Cursor size
///
/// </value>
/// <exception cref="ArgumentOutOfRangeException">
///
/// If set to under 0 or over 100
///
/// </exception>
/// <exception cref="HostException">
///
/// If obtaining a handle to the active screen buffer failed
/// OR
/// Win32's GetConsoleCursorInfo failed
/// OR
/// Win32's SetConsoleCursorInfo failed
///
/// </exception>
public override
int
CursorSize
{
get
{
ConsoleHandle consoleHandle = ConsoleControl.GetActiveScreenBufferHandle();
int size = (int)ConsoleControl.GetConsoleCursorInfo(consoleHandle).Size;
return size;
}
set
{
const int MinCursorSize = 0;
const int MaxCursorSize = 100;
if (value >= MinCursorSize && value <= MaxCursorSize)
{
ConsoleHandle consoleHandle = ConsoleControl.GetActiveScreenBufferHandle();
ConsoleControl.CONSOLE_CURSOR_INFO cursorInfo =
ConsoleControl.GetConsoleCursorInfo(consoleHandle);
if (value == 0)
{
cursorInfo.Visible = false;
}
else
{
cursorInfo.Size = (uint)value;
cursorInfo.Visible = true;
}
ConsoleControl.SetConsoleCursorInfo(consoleHandle, cursorInfo);
}
else
{
throw PSTraceSource.NewArgumentOutOfRangeException("value", value,
ConsoleHostRawUserInterfaceStrings.InvalidCursorSizeError);
}
}
}
/// <summary>
///
/// See base class
///
/// </summary>
/// <value></value>
/// <exception cref="ArgumentOutOfRangeException">
///
/// If set outside of the buffer
///
/// </exception>
/// <exception cref="HostException">
///
/// If obtaining information about the buffer failed
/// OR
/// Win32's SetConsoleWindowInfo failed
///
/// </exception>
public override
Coordinates
WindowPosition
{
get
{
ConsoleControl.CONSOLE_SCREEN_BUFFER_INFO bufferInfo;
GetBufferInfo(out bufferInfo);
Coordinates c = new Coordinates(bufferInfo.WindowRect.Left, bufferInfo.WindowRect.Top);
return c;
}
set
{
ConsoleControl.CONSOLE_SCREEN_BUFFER_INFO bufferInfo;
ConsoleHandle handle = GetBufferInfo(out bufferInfo);
ConsoleControl.SMALL_RECT r = bufferInfo.WindowRect;
// the dimensions of the window can't extend past the dimensions of the screen buffer. This means that the
// X position of the window is limited to the buffer width minus one minus the window width, and the Y
// position of the window is limited to the buffer height minus one minus the window height.
int windowWidth = r.Right - r.Left + 1;
int windowHeight = r.Bottom - r.Top + 1;
if (value.X < 0 || value.X > bufferInfo.BufferSize.X - windowWidth)
{
throw PSTraceSource.NewArgumentOutOfRangeException("value.X", value.X,
ConsoleHostRawUserInterfaceStrings.InvalidXWindowPositionError);
}
if (value.Y < 0 || value.Y > bufferInfo.BufferSize.Y - windowHeight)
{
throw PSTraceSource.NewArgumentOutOfRangeException("value.Y", value.Y,
ConsoleHostRawUserInterfaceStrings.InvalidYWindowPositionError);
}
r.Left = (short)value.X;
r.Top = (short)value.Y;
// subtract 1 from each dimension because the semantics of the win32 api are not "number of characters in
// span" but "starting and ending position"
r.Right = (short)(r.Left + windowWidth - 1);
r.Bottom = (short)(r.Top + windowHeight - 1);
Dbg.Assert(r.Right >= r.Left, "Window size is too narrow");
Dbg.Assert(r.Bottom >= r.Top, "Window size is too short");
ConsoleControl.SetConsoleWindowInfo(handle, true, r);
}
}
/// <summary>
///
/// See base class
///
/// </summary>
/// <value></value>
/// <exception cref="ArgumentOutOfRangeException">
///
/// If setting to an invalid size
///
/// </exception>
/// <exception cref="HostException">
///
/// If obtaining a handle to the active screen buffer failed
/// OR
/// obtaining information about the buffer failed
/// OR
/// Win32's SetConsoleScreenBufferSize failed
///
/// </exception>
public override
Size
BufferSize
{
get
{
ConsoleControl.CONSOLE_SCREEN_BUFFER_INFO bufferInfo;
GetBufferInfo(out bufferInfo);
return new Size(bufferInfo.BufferSize.X, bufferInfo.BufferSize.Y);
}
set
{
// looking in windows/core/ntcon/server/output.c, it looks like the minimum size is 1 row X however many
// characters will fit in the minimum window size system metric (SM_CXMIN). Instead of going to the effort of
// computing that minimum here, it is cleaner and cheaper to make the call to SetConsoleScreenBuffer and just
// translate any exception that might get thrown.
try
{
ConsoleHandle handle = ConsoleControl.GetActiveScreenBufferHandle();
ConsoleControl.SetConsoleScreenBufferSize(handle, value);
}
catch (HostException e)
{
Win32Exception win32exception = e.InnerException as Win32Exception;
if (win32exception != null &&
win32exception.NativeErrorCode == 0x57)
{
throw PSTraceSource.NewArgumentOutOfRangeException("value", value,
ConsoleHostRawUserInterfaceStrings.InvalidBufferSizeError);
}
else
{
throw;
}
}
}
}
/// <summary>
///
/// See base class
///
/// </summary>
/// <value></value>
/// <exception cref="ArgumentOutOfRangeException">
///
/// If setting width or height to less than 1, larger than the screen buffer,
/// over the maximum window size allowed
///
/// </exception>
/// <exception cref="HostException">
///
/// If obtaining information about the buffer failed
/// OR
/// Win32's SetConsoleWindowInfo failed
///
/// </exception>
public override
Size
WindowSize
{
get
{
ConsoleControl.CONSOLE_SCREEN_BUFFER_INFO bufferInfo;
GetBufferInfo(out bufferInfo);
Size s =
new Size(
bufferInfo.WindowRect.Right - bufferInfo.WindowRect.Left + 1,
bufferInfo.WindowRect.Bottom - bufferInfo.WindowRect.Top + 1);
return s;
}
set
{
ConsoleControl.CONSOLE_SCREEN_BUFFER_INFO bufferInfo;
ConsoleHandle handle = GetBufferInfo(out bufferInfo);
// the dimensions of the window can't extend past the dimensions of the screen buffer. This means that the
// width of the window is limited to the buffer width minus one minus the window X position, and the height
// of the window is limited to the buffer height minus one minus the window Y position.
if (value.Width < 1)
{
throw PSTraceSource.NewArgumentOutOfRangeException("value.Width", value.Width,
ConsoleHostRawUserInterfaceStrings.WindowWidthTooSmallError);
}
if (value.Height < 1)
{
throw PSTraceSource.NewArgumentOutOfRangeException("value.Height", value.Height,
ConsoleHostRawUserInterfaceStrings.WindowHeightTooSmallError);
}
if (value.Width > bufferInfo.BufferSize.X)
{
throw PSTraceSource.NewArgumentOutOfRangeException("value.Width", value.Width,
ConsoleHostRawUserInterfaceStrings.WindowWidthLargerThanBufferError);
}
if (value.Height > bufferInfo.BufferSize.Y)
{
throw PSTraceSource.NewArgumentOutOfRangeException("value.Height", value.Height,
ConsoleHostRawUserInterfaceStrings.WindowHeightLargerThanBufferError);
}
if (value.Width > bufferInfo.MaxWindowSize.X)
{
throw PSTraceSource.NewArgumentOutOfRangeException("value.Width", value.Width,
ConsoleHostRawUserInterfaceStrings.WindowWidthTooLargeErrorTemplate,
bufferInfo.MaxWindowSize.X);
}
if (value.Height > bufferInfo.MaxWindowSize.Y)
{
throw PSTraceSource.NewArgumentOutOfRangeException("value.Height", value.Height,
ConsoleHostRawUserInterfaceStrings.WindowHeightTooLargeErrorTemplate,
bufferInfo.MaxWindowSize.Y);
}
// if the new size will extend past the edge of screen buffer, then move the window position to try to
// accomodate that.
ConsoleControl.SMALL_RECT r = bufferInfo.WindowRect;
// subtract 1 from each dimension because the semantics of the win32 api are not "number of characters in
// span" but "starting and ending position"
r.Right = (short)(r.Left + value.Width - 1);
r.Bottom = (short)(r.Top + value.Height - 1);
// Now we check if the bottom right coordinate of our window went over the coordinate of the bottom
// right of the buffer. If it did then we need to adjust the window.
// bufferInfo.BufferSize.X - 1 will give us the rightmost coordinate of the buffer.
// r.Right - rightCoordinateOfBuffer will give us how much we need to adjust the window left and right coordinates.
// Then we can do the same for top and bottom.
short adjustLeft = (short)(r.Right - (bufferInfo.BufferSize.X - 1));
short adjustTop = (short)(r.Bottom - (bufferInfo.BufferSize.Y - 1));
if (adjustLeft > 0)
{
r.Left -= adjustLeft;
r.Right -= adjustLeft;
}
if (adjustTop > 0)
{
r.Top -= adjustTop;
r.Bottom -= adjustTop;
}
if (r.Right < r.Left)
{
throw PSTraceSource.NewArgumentOutOfRangeException("value", value,
ConsoleHostRawUserInterfaceStrings.WindowTooNarrowError);
}
if (r.Bottom < r.Top)
{
throw PSTraceSource.NewArgumentOutOfRangeException("value", value,
ConsoleHostRawUserInterfaceStrings.WindowTooShortError);
}
ConsoleControl.SetConsoleWindowInfo(handle, true, r);
}
}
/// <summary>
///
/// See base class
///
/// </summary>
/// <value></value>
/// <exception cref="HostException">
///
/// If obtaining information about the buffer failed
///
/// </exception>
public override
Size
MaxWindowSize
{
get
{
ConsoleControl.CONSOLE_SCREEN_BUFFER_INFO bufferInfo;
GetBufferInfo(out bufferInfo);
Size s = new Size(bufferInfo.MaxWindowSize.X, bufferInfo.MaxWindowSize.Y);
return s;
}
}
/// <summary>
///
/// See base class
///
/// </summary>
/// <value></value>
/// <exception cref="HostException">
///
/// If obtaining a handle to the active screen buffer failed
/// OR
/// Win32's GetLargestConsoleWindowSize failed
///
/// </exception>
public override
Size
MaxPhysicalWindowSize
{
get
{
ConsoleHandle handle = ConsoleControl.GetActiveScreenBufferHandle();
return ConsoleControl.GetLargestConsoleWindowSize(handle);
}
}
/// <summary>
/// Helper method to create and trace PipelineStoppedException
/// </summary>
/// <returns></returns>
private PipelineStoppedException NewPipelineStoppedException()
{
PipelineStoppedException e = new PipelineStoppedException();
return e;
}
/// <summary>
/// Used by ReadKey, cache KeyEvent based on if input.RepeatCount > 1
/// </summary>
/// <param name="input">Input key event record</param>
/// <param name="cache">Cache key event</param>
private static void CacheKeyEvent(ConsoleControl.KEY_EVENT_RECORD input, ref ConsoleControl.KEY_EVENT_RECORD cache)
{
if (input.RepeatCount > 1)
{
cache = input;
cache.RepeatCount--;
}
}
/// <summary>
///
/// See base class
/// This method unwraps the repeat count in KEY_EVENT_RECORD by caching repeated keystrokes
/// in a logical queue. The implications are:
/// 1) Per discussion with Sburns on 2005/01/20, calling this method with allowCtrlC | includeKeyUp may not
/// return ctrl-c even it is pressed. This is because ctrl-c could generate the following sequence of
/// key events: {Ctrl, KeyDown}, {Ctrl-c KeyDown}, {Ctrl, KeyUp}, {c, KeyUp} if Ctrl is released before c.
/// In this case, {Ctrl, KeyUp}, {c, KeyUp} would be returned.
/// 2) If the cache is non-empty, a call to ReadLine will not return the cached keys. This
/// behavior is the same as that of System.Console.ReadKey
///
/// </summary>
/// <param name="options"></param>
/// <returns></returns>
/// <exception cref="ArgumentException">
///
/// If neither IncludeKeyDown or IncludeKeyUp is set in <paramref name="options"/>
///
/// </exception>
/// <exception cref="HostException">
///
/// If obtaining a handle to the active screen buffer failed
/// OR
/// Win32's setting input buffer mode to disregard window and mouse input failed
/// OR
/// Win32's ReadConsoleInput failed
///
/// </exception>
public override
KeyInfo
ReadKey(ReadKeyOptions options)
{
if ((options & (ReadKeyOptions.IncludeKeyDown | ReadKeyOptions.IncludeKeyUp)) == 0)
{
throw PSTraceSource.NewArgumentException("options", ConsoleHostRawUserInterfaceStrings.InvalidReadKeyOptionsError);
}
// keyInfo is initialized in the below if-else statement
KeyInfo keyInfo;
if (cachedKeyEvent.RepeatCount > 0)
{
// Ctrl-C is not allowed and Ctrl-C is cached.
if (((options & ReadKeyOptions.AllowCtrlC) == 0) && cachedKeyEvent.UnicodeChar == (char)3)
{
// Ctrl-C is in the cache, stop pipeline immediately
cachedKeyEvent.RepeatCount--;
throw NewPipelineStoppedException();
}
// If IncludeKeyUp is not set and cached key events are KeyUp OR
// IncludeKeyDown is not set and cached key events are KeyDown, clear the cache
if ((((options & ReadKeyOptions.IncludeKeyUp) == 0) && !cachedKeyEvent.KeyDown) ||
(((options & ReadKeyOptions.IncludeKeyDown) == 0) && cachedKeyEvent.KeyDown))
{
cachedKeyEvent.RepeatCount = 0;
}
}
if (cachedKeyEvent.RepeatCount > 0)
{
KEY_EVENT_RECORDToKeyInfo(cachedKeyEvent, out keyInfo);
cachedKeyEvent.RepeatCount--;
}
else
{
ConsoleHandle handle = ConsoleControl.GetConioDeviceHandle();
ConsoleControl.INPUT_RECORD[] inputRecords = new ConsoleControl.INPUT_RECORD[1];
ConsoleControl.ConsoleModes originalMode = ConsoleControl.GetMode(handle);
// set input mode to exclude mouse or window events
// turn off ProcessedInput flag to handle ctrl-c
ConsoleControl.ConsoleModes newMode = originalMode &
~ConsoleControl.ConsoleModes.WindowInput &
~ConsoleControl.ConsoleModes.MouseInput &
~ConsoleControl.ConsoleModes.ProcessedInput;
try
{
ConsoleControl.SetMode(handle, newMode);
while (true)
{
int actualNumberOfInput = ConsoleControl.ReadConsoleInput(handle, ref inputRecords);
Dbg.Assert(actualNumberOfInput == 1,
string.Format(CultureInfo.InvariantCulture, "ReadConsoleInput returns {0} number of input event records",
actualNumberOfInput));
if (actualNumberOfInput == 1)
{
if (((ConsoleControl.InputRecordEventTypes)inputRecords[0].EventType) ==
ConsoleControl.InputRecordEventTypes.KEY_EVENT)
{
Dbg.Assert((inputRecords[0].KeyEvent.KeyDown && inputRecords[0].KeyEvent.RepeatCount != 0) ||
!inputRecords[0].KeyEvent.KeyDown,
string.Format(CultureInfo.InvariantCulture, "ReadConsoleInput returns a KeyEvent that is KeyDown and RepeatCount 0"));
if (inputRecords[0].KeyEvent.RepeatCount == 0)
{
// Sometimes Win32 ReadConsoleInput returns a KeyEvent record whose
// RepeatCount is zero. This type of record does not
// represent a keystroke.
continue;
}
// Ctrl-C is not allowed and Ctrl-C is input
if ((options & ReadKeyOptions.AllowCtrlC) == 0 &&
inputRecords[0].KeyEvent.UnicodeChar == (char)3)
{
CacheKeyEvent(inputRecords[0].KeyEvent, ref cachedKeyEvent);
throw NewPipelineStoppedException();
}
// if KeyDown events are wanted and event is KeyDown OR
// KeyUp events are wanted and event is KeyUp
if ((((options & ReadKeyOptions.IncludeKeyDown) != 0) &&
inputRecords[0].KeyEvent.KeyDown) ||
(((options & ReadKeyOptions.IncludeKeyUp) != 0) &&
!inputRecords[0].KeyEvent.KeyDown))
{
CacheKeyEvent(inputRecords[0].KeyEvent, ref cachedKeyEvent);
KEY_EVENT_RECORDToKeyInfo(inputRecords[0].KeyEvent, out keyInfo);
break;
}
}
}
}
}
finally
{
ConsoleControl.SetMode(handle, originalMode);
}
}
if ((options & ReadKeyOptions.NoEcho) == 0)
{
parent.WriteToConsole(
keyInfo.Character.ToString(),
true);
}
return keyInfo;
}
private static
void
KEY_EVENT_RECORDToKeyInfo(ConsoleControl.KEY_EVENT_RECORD keyEventRecord, out KeyInfo keyInfo)
{
keyInfo = new KeyInfo(
keyEventRecord.VirtualKeyCode,
keyEventRecord.UnicodeChar,
(ControlKeyStates)keyEventRecord.ControlKeyState,
keyEventRecord.KeyDown);
}
/// <summary>
///
/// See base class
///
/// </summary>
/// <exception cref="HostException">
///
/// If obtaining a handle to the active screen buffer failed
/// OR
/// Win32's FlushConsoleInputBuffer failed
///
/// </exception>
public override
void
FlushInputBuffer()
{
ConsoleHandle handle = ConsoleControl.GetConioDeviceHandle();
ConsoleControl.FlushConsoleInputBuffer(handle);
cachedKeyEvent.RepeatCount = 0;
}
/// <summary>
///
/// See base class
///
/// </summary>
/// <returns></returns>
/// <exception cref="HostException">
///
/// If obtaining a handle to the active screen buffer failed
/// OR
/// Win32's GetNumberOfConsoleInputEvents failed
/// OR
/// Win32's PeekConsoleInput failed
///
/// </exception>
public override
bool
KeyAvailable
{
get
{
if (cachedKeyEvent.RepeatCount > 0)
{
return true;
}
ConsoleHandle handle = ConsoleControl.GetConioDeviceHandle();
ConsoleControl.INPUT_RECORD[] inputRecords =
new ConsoleControl.INPUT_RECORD[ConsoleControl.GetNumberOfConsoleInputEvents(handle)];
int actualNumberOfInputRecords = ConsoleControl.PeekConsoleInput(handle, ref inputRecords);
for (int i = 0; i < actualNumberOfInputRecords; i++)
{
if (((ConsoleControl.InputRecordEventTypes)inputRecords[i].EventType) ==
ConsoleControl.InputRecordEventTypes.KEY_EVENT)
{
Dbg.Assert((inputRecords[i].KeyEvent.KeyDown && inputRecords[i].KeyEvent.RepeatCount != 0) ||
!inputRecords[i].KeyEvent.KeyDown,
string.Format(CultureInfo.InvariantCulture, "PeekConsoleInput returns a KeyEvent that is KeyDown and RepeatCount 0"));
if (inputRecords[i].KeyEvent.KeyDown && inputRecords[i].KeyEvent.RepeatCount == 0)
{
// Sometimes Win32 ReadConsoleInput returns a KeyEvent record whose
// KeyDown is true and RepeatCount is zero. This type of record does not
// represent a keystroke.
continue;
}
return true;
}
}
return false;
}
}
/// <summary>
///
/// See base class
///
/// </summary>
/// <value></value>
/// <exception cref="ArgumentNullException">
///
/// If set to null
///
/// </exception>
/// <exception cref="ArgumentException">
///
/// If set to a string whose length is not between 1 to 1023
///
/// </exception>
/// <exception cref="HostException">
///
/// If Win32's GetConsoleWindowTitle failed
/// OR
/// Win32's SetConsoleWindowTitle failed
///
/// </exception>
public override string WindowTitle
{
get
{
return ConsoleControl.GetConsoleWindowTitle();
}
set
{
const int MaxWindowTitleLength = 1023;
const int MinWindowTitleLength = 0;
if (value != null)
{
if (
value.Length >= MinWindowTitleLength &&
value.Length <= MaxWindowTitleLength
)
{
ConsoleControl.SetConsoleWindowTitle(value);
}
else if (value.Length < MinWindowTitleLength)
{
throw PSTraceSource.NewArgumentException("value", ConsoleHostRawUserInterfaceStrings.WindowTitleTooShortError);
}
else
{
throw PSTraceSource.NewArgumentException("value",
ConsoleHostRawUserInterfaceStrings
.WindowTitleTooLongErrorTemplate,
MaxWindowTitleLength);
}
}
else
{
throw PSTraceSource.NewArgumentNullException("value");
}
}
}
/// <summary>
///
/// See base class.
///
///
/// </summary>
/// <param name="origin">
///
/// location on screen buffer where contents will be written
///
/// </param>
/// <param name="contents">
///
/// array of info to be written
///
/// </param>
/// <remarks></remarks>
/// <exception cref="ArgumentOutOfRangeException">
///
/// If <paramref name="origin"/> is outside of the screen buffer.
/// OR
/// <paramref name="contents"/> is an ill-formed BufferCell array
/// OR
/// it is illegal to write <paramref name="contents"/> at <paramref name="origin"/> in the buffer
///
/// </exception>
/// <exception cref="HostException">
///
/// If obtaining a handle to the active screen buffer failed
/// OR
/// obtaining information about the buffer failed
/// OR
/// there is not enough memory to complete calls to Win32's WriteConsoleOutput
///
/// </exception>
public override
void
SetBufferContents(Coordinates origin, BufferCell[,] contents)
{
if (contents == null)
{
PSTraceSource.NewArgumentNullException("contents");
}
// the origin must be within the window.
ConsoleControl.CONSOLE_SCREEN_BUFFER_INFO bufferInfo;
ConsoleHandle handle = GetBufferInfo(out bufferInfo);