2 // System.WindowsConsoleDriver
5 // Gonzalo Paniagua Javier (gonzalo@ximian.com)
7 // (C) 2005 Novell, Inc. (http://www.novell.com)
10 // Permission is hereby granted, free of charge, to any person obtaining
11 // a copy of this software and associated documentation files (the
12 // "Software"), to deal in the Software without restriction, including
13 // without limitation the rights to use, copy, modify, merge, publish,
14 // distribute, sublicense, and/or sell copies of the Software, and to
15 // permit persons to whom the Software is furnished to do so, subject to
16 // the following conditions:
18 // The above copyright notice and this permission notice shall be
19 // included in all copies or substantial portions of the Software.
21 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
22 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
23 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
24 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
25 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
26 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
27 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
30 using System.Runtime.InteropServices;
33 struct ConsoleCursorInfo {
39 public short EventType;
40 // This is KEY_EVENT_RECORD
42 public short RepeatCount;
43 public short VirtualKeyCode;
44 public short VirtualScanCode;
45 public char Character;
46 public int ControlKeyState;
53 public char Character;
54 public short Attributes;
61 public Coord (int x, int y)
74 public SmallRect (int left, int top, int right, int bottom)
78 Right = (short) right;
79 Bottom = (short) bottom;
83 struct ConsoleScreenBufferInfo {
85 public Coord CursorPosition;
86 public short Attribute;
87 public SmallRect Window;
88 public Coord MaxWindowSize;
97 unsafe class WindowsConsoleDriver : IConsoleDriver {
100 short defaultAttribute;
103 public WindowsConsoleDriver ()
105 outputHandle = GetStdHandle (Handles.STD_OUTPUT);
106 inputHandle = GetStdHandle (Handles.STD_INPUT);
107 ConsoleScreenBufferInfo info = new ConsoleScreenBufferInfo ();
108 GetConsoleScreenBufferInfo (outputHandle, out info);
109 defaultAttribute = info.Attribute; // Not sure about this...
113 // FOREGROUND_GREEN 2
115 // FOREGROUND_INTENSITY 8
116 // BACKGROUND_BLUE 16
117 // BACKGROUND_GREEN 32
119 // BACKGROUND_INTENSITY 128
120 static ConsoleColor GetForeground (short attr)
123 return (ConsoleColor) attr;
126 static ConsoleColor GetBackground (short attr)
130 return (ConsoleColor) attr;
133 static short GetAttrForeground (int attr, ConsoleColor color)
136 return (short) (attr | (int) color);
139 static short GetAttrBackground (int attr, ConsoleColor color)
142 int c = ((int) color) << 4;
143 return (short) (attr | c);
146 public ConsoleColor BackgroundColor {
148 ConsoleScreenBufferInfo info = new ConsoleScreenBufferInfo ();
149 GetConsoleScreenBufferInfo (outputHandle, out info);
150 return GetBackground (info.Attribute);
153 ConsoleScreenBufferInfo info = new ConsoleScreenBufferInfo ();
154 GetConsoleScreenBufferInfo (outputHandle, out info);
155 short attr = GetAttrBackground (info.Attribute, value);
156 SetConsoleTextAttribute (outputHandle, attr);
160 public int BufferHeight {
162 ConsoleScreenBufferInfo info = new ConsoleScreenBufferInfo ();
163 GetConsoleScreenBufferInfo (outputHandle, out info);
166 set { SetBufferSize (BufferWidth, value); }
169 public int BufferWidth {
171 ConsoleScreenBufferInfo info = new ConsoleScreenBufferInfo ();
172 GetConsoleScreenBufferInfo (outputHandle, out info);
175 set { SetBufferSize (value, BufferHeight); }
178 public bool CapsLock {
180 short state = GetKeyState (20); // VK_CAPITAL
181 return ((state & 1) == 1);
185 public int CursorLeft {
187 ConsoleScreenBufferInfo info = new ConsoleScreenBufferInfo ();
188 GetConsoleScreenBufferInfo (outputHandle, out info);
189 return info.CursorPosition.X;
191 set { SetCursorPosition (value, CursorTop); }
194 public int CursorSize {
196 ConsoleCursorInfo info = new ConsoleCursorInfo ();
197 GetConsoleCursorInfo (outputHandle, out info);
201 if (value < 1 || value > 100)
202 throw new ArgumentOutOfRangeException ("value");
204 ConsoleCursorInfo info = new ConsoleCursorInfo ();
205 GetConsoleCursorInfo (outputHandle, out info);
207 if (!SetConsoleCursorInfo (outputHandle, ref info))
208 throw new Exception ("SetConsoleCursorInfo failed");
212 public int CursorTop {
214 ConsoleScreenBufferInfo info = new ConsoleScreenBufferInfo ();
215 GetConsoleScreenBufferInfo (outputHandle, out info);
216 return info.CursorPosition.Y;
218 set { SetCursorPosition (CursorLeft, value); }
221 public bool CursorVisible {
223 ConsoleCursorInfo info = new ConsoleCursorInfo ();
224 GetConsoleCursorInfo (outputHandle, out info);
228 ConsoleCursorInfo info = new ConsoleCursorInfo ();
229 GetConsoleCursorInfo (outputHandle, out info);
230 if (info.Visible == value)
233 info.Visible = value;
234 if (!SetConsoleCursorInfo (outputHandle, ref info))
235 throw new Exception ("SetConsoleCursorInfo failed");
239 public bool Echo { // not really used on windows
244 public ConsoleColor ForegroundColor {
246 ConsoleScreenBufferInfo info = new ConsoleScreenBufferInfo ();
247 GetConsoleScreenBufferInfo (outputHandle, out info);
248 return GetForeground (info.Attribute);
251 ConsoleScreenBufferInfo info = new ConsoleScreenBufferInfo ();
252 GetConsoleScreenBufferInfo (outputHandle, out info);
253 short attr = GetAttrForeground (info.Attribute, value);
254 SetConsoleTextAttribute (outputHandle, attr);
258 public bool KeyAvailable {
261 InputRecord record = new InputRecord ();
263 // Use GetNumberOfConsoleInputEvents and remove the while?
264 if (!PeekConsoleInput (inputHandle, out record, 1, out eventsRead))
265 throw new InvalidOperationException ("Error in PeekConsoleInput " +
266 Marshal.GetLastWin32Error ());
272 if (record.EventType == 1 && record.KeyDown)
275 if (!ReadConsoleInput (inputHandle, out record, 1, out eventsRead))
276 throw new InvalidOperationException ("Error in ReadConsoleInput " +
277 Marshal.GetLastWin32Error ());
282 public bool Initialized { // Not useful on windows, so false.
283 get { return false; }
286 public int LargestWindowHeight {
288 Coord coord = GetLargestConsoleWindowSize (outputHandle);
289 if (coord.X == 0 && coord.Y == 0)
290 throw new Exception ("GetLargestConsoleWindowSize" + Marshal.GetLastWin32Error ());
296 public int LargestWindowWidth {
298 Coord coord = GetLargestConsoleWindowSize (outputHandle);
299 if (coord.X == 0 && coord.Y == 0)
300 throw new Exception ("GetLargestConsoleWindowSize" + Marshal.GetLastWin32Error ());
306 public bool NumberLock {
308 short state = GetKeyState (144); // VK_NUMLOCK
309 return ((state & 1) == 1);
313 public string Title {
315 StringBuilder sb = new StringBuilder (1024); // hope this is enough
316 if (GetConsoleTitle (sb, 1024) == 0) {
318 sb = new StringBuilder (26001);
319 if (GetConsoleTitle (sb, 26000) == 0)
320 throw new Exception ("Got " + Marshal.GetLastWin32Error ());
323 return sb.ToString ();
327 throw new ArgumentNullException ("value");
329 if (!SetConsoleTitle (value))
330 throw new Exception ("Got " + Marshal.GetLastWin32Error ());
334 public bool TreatControlCAsInput {
337 if (!GetConsoleMode (outputHandle, out mode))
338 throw new Exception ("Failed in GetConsoleMode: " + Marshal.GetLastWin32Error ());
340 // ENABLE_PROCESSED_INPUT
341 return ((mode & 1) == 0);
346 if (!GetConsoleMode (outputHandle, out mode))
347 throw new Exception ("Failed in GetConsoleMode: " + Marshal.GetLastWin32Error ());
349 bool cAsInput = ((mode & 1) == 0);
350 if (cAsInput == value)
358 if (!SetConsoleMode (outputHandle, mode))
359 throw new Exception ("Failed in SetConsoleMode: " + Marshal.GetLastWin32Error ());
363 public int WindowHeight {
365 ConsoleScreenBufferInfo info = new ConsoleScreenBufferInfo ();
366 GetConsoleScreenBufferInfo (outputHandle, out info);
367 return info.Window.Bottom - info.Window.Top + 1;
369 set { SetWindowSize (WindowWidth, value); }
372 public int WindowLeft {
374 ConsoleScreenBufferInfo info = new ConsoleScreenBufferInfo ();
375 GetConsoleScreenBufferInfo (outputHandle, out info);
376 return info.Window.Left;
378 set { SetWindowPosition (value, WindowTop); }
381 public int WindowTop {
383 ConsoleScreenBufferInfo info = new ConsoleScreenBufferInfo ();
384 GetConsoleScreenBufferInfo (outputHandle, out info);
385 return info.Window.Top;
387 set { SetWindowPosition (WindowLeft, value); }
390 public int WindowWidth {
392 ConsoleScreenBufferInfo info = new ConsoleScreenBufferInfo ();
393 GetConsoleScreenBufferInfo (outputHandle, out info);
394 return info.Window.Right - info.Window.Left + 1;
396 set { SetWindowSize (value, WindowHeight); }
399 public void Beep (int frequency, int duration)
401 _Beep (frequency, duration);
406 Coord coord = new Coord ();
407 ConsoleScreenBufferInfo info = new ConsoleScreenBufferInfo ();
408 GetConsoleScreenBufferInfo (outputHandle, out info);
410 int size = info.Size.X * info.Size.Y;
412 FillConsoleOutputCharacter (outputHandle, ' ', size, coord, out written);
414 GetConsoleScreenBufferInfo (outputHandle, out info);
416 FillConsoleOutputAttribute (outputHandle, info.Attribute, size, coord, out written);
417 SetConsoleCursorPosition (outputHandle, coord);
420 public void MoveBufferArea (int sourceLeft, int sourceTop, int sourceWidth, int sourceHeight,
421 int targetLeft, int targetTop, Char sourceChar,
422 ConsoleColor sourceForeColor, ConsoleColor sourceBackColor)
424 if (sourceForeColor < 0)
425 throw new ArgumentException ("Cannot be less than 0.", "sourceForeColor");
427 if (sourceBackColor < 0)
428 throw new ArgumentException ("Cannot be less than 0.", "sourceBackColor");
430 if (sourceWidth == 0 || sourceHeight == 0)
433 ConsoleScreenBufferInfo info = new ConsoleScreenBufferInfo ();
434 GetConsoleScreenBufferInfo (outputHandle, out info);
435 CharInfo [] buffer = new CharInfo [sourceWidth * sourceHeight];
436 Coord bsize = new Coord (sourceWidth, sourceHeight);
437 Coord bpos = new Coord (0, 0);
438 SmallRect region = new SmallRect (sourceLeft, sourceTop, sourceLeft + sourceWidth - 1, sourceTop + sourceHeight - 1);
439 fixed (void *ptr = &buffer [0]) {
440 if (!ReadConsoleOutput (outputHandle, ptr, bsize, bpos, ref region))
441 throw new ArgumentException ("", "Cannot read from the specified coordinates.");
445 short attr = GetAttrForeground (0, sourceForeColor);
446 attr = GetAttrBackground (attr, sourceBackColor);
447 bpos = new Coord (sourceLeft, sourceTop);
448 for (int i = 0; i < sourceHeight; i++, bpos.Y++) {
449 FillConsoleOutputCharacter (outputHandle, sourceChar, sourceWidth, bpos, out written);
450 FillConsoleOutputAttribute (outputHandle, attr, sourceWidth, bpos, out written);
453 bpos = new Coord (0, 0);
454 region = new SmallRect (targetLeft, targetTop, targetLeft + sourceWidth - 1, targetTop + sourceHeight - 1);
455 if (!WriteConsoleOutput (outputHandle, buffer, bsize, bpos, ref region))
456 throw new ArgumentException ("", "Cannot write to the specified coordinates.");
459 public ConsoleKeyInfo ReadKey (bool intercept)
462 InputRecord record = new InputRecord ();
464 if (!ReadConsoleInput (inputHandle, out record, 1, out eventsRead))
465 throw new InvalidOperationException ("Error in ReadConsoleInput " +
466 Marshal.GetLastWin32Error ());
467 } while (record.EventType != 1 && !record.KeyDown);
469 // RIGHT_ALT_PRESSED 1
470 // LEFT_ALT_PRESSED 2
471 // RIGHT_CTRL_PRESSED 4
472 // LEFT_CTRL_PRESSED 8
474 bool alt = ((record.ControlKeyState & 3) != 0);
475 bool ctrl = ((record.ControlKeyState & 12) != 0);
476 bool shift = ((record.ControlKeyState & 16) != 0);
477 return new ConsoleKeyInfo (record.Character, (ConsoleKey) record.VirtualKeyCode, shift, alt, ctrl);
480 public void ResetColor ()
482 SetConsoleTextAttribute (outputHandle, defaultAttribute);
485 public void SetBufferSize (int width, int height)
487 ConsoleScreenBufferInfo info = new ConsoleScreenBufferInfo ();
488 GetConsoleScreenBufferInfo (outputHandle, out info);
490 if (width - 1 > info.Window.Right)
491 throw new ArgumentOutOfRangeException ("width");
493 if (height - 1 > info.Window.Bottom)
494 throw new ArgumentOutOfRangeException ("height");
496 Coord coord = new Coord (width, height);
497 if (!SetConsoleScreenBufferSize (outputHandle, coord))
498 throw new ArgumentOutOfRangeException ("height/width", "Cannot be smaller than the window size.");
501 public void SetCursorPosition (int left, int top)
503 Coord coord = new Coord (left, top);
504 SetConsoleCursorPosition (outputHandle, coord);
507 public void SetWindowPosition (int left, int top)
509 ConsoleScreenBufferInfo info = new ConsoleScreenBufferInfo ();
510 GetConsoleScreenBufferInfo (outputHandle, out info);
511 SmallRect rect = info.Window;
512 rect.Left = (short) left;
513 rect.Top = (short) top;
514 if (!SetConsoleWindowInfo (outputHandle, true, ref rect))
515 throw new ArgumentOutOfRangeException ("left/top", "Windows error " + Marshal.GetLastWin32Error ());
518 public void SetWindowSize (int width, int height)
520 ConsoleScreenBufferInfo info = new ConsoleScreenBufferInfo ();
521 GetConsoleScreenBufferInfo (outputHandle, out info);
522 SmallRect rect = info.Window;
523 rect.Right = (short) (rect.Left + width - 1);
524 rect.Bottom = (short) (rect.Top + height - 1);
525 if (!SetConsoleWindowInfo (outputHandle, true, ref rect))
526 throw new ArgumentOutOfRangeException ("left/top", "Windows error " + Marshal.GetLastWin32Error ());
532 [DllImport ("kernel32.dll", EntryPoint="GetStdHandle", SetLastError=true, CharSet=CharSet.Unicode)]
533 extern static IntPtr GetStdHandle (Handles handle);
535 [DllImport ("kernel32.dll", EntryPoint="Beep", SetLastError=true, CharSet=CharSet.Unicode)]
536 extern static void _Beep (int frequency, int duration);
538 [DllImport ("kernel32.dll", EntryPoint="GetConsoleScreenBufferInfo", SetLastError=true, CharSet=CharSet.Unicode)]
539 extern static bool GetConsoleScreenBufferInfo (IntPtr handle, out ConsoleScreenBufferInfo info);
541 [DllImport ("kernel32.dll", EntryPoint="FillConsoleOutputCharacter", SetLastError=true, CharSet=CharSet.Unicode)]
542 extern static bool FillConsoleOutputCharacter (IntPtr handle, char c, int size, Coord coord, out int written);
544 [DllImport ("kernel32.dll", EntryPoint="FillConsoleOutputAttribute", SetLastError=true, CharSet=CharSet.Unicode)]
545 extern static bool FillConsoleOutputAttribute (IntPtr handle, short c, int size, Coord coord, out int written);
547 [DllImport ("kernel32.dll", EntryPoint="SetConsoleCursorPosition", SetLastError=true, CharSet=CharSet.Unicode)]
548 extern static bool SetConsoleCursorPosition (IntPtr handle, Coord coord);
550 [DllImport ("kernel32.dll", EntryPoint="SetConsoleTextAttribute", SetLastError=true, CharSet=CharSet.Unicode)]
551 extern static bool SetConsoleTextAttribute (IntPtr handle, short attribute);
553 [DllImport ("kernel32.dll", EntryPoint="SetConsoleScreenBufferSize", SetLastError=true, CharSet=CharSet.Unicode)]
554 extern static bool SetConsoleScreenBufferSize (IntPtr handle, Coord newSize);
556 [DllImport ("kernel32.dll", EntryPoint="SetConsoleWindowInfo", SetLastError=true, CharSet=CharSet.Unicode)]
557 extern static bool SetConsoleWindowInfo (IntPtr handle, bool absolute, ref SmallRect rect);
559 [DllImport ("kernel32.dll", EntryPoint="GetConsoleTitle", SetLastError=true, CharSet=CharSet.Unicode)]
560 extern static int GetConsoleTitle (StringBuilder sb, int size);
562 [DllImport ("kernel32.dll", EntryPoint="SetConsoleTitle", SetLastError=true, CharSet=CharSet.Unicode)]
563 extern static bool SetConsoleTitle (string title);
565 [DllImport ("kernel32.dll", EntryPoint="GetConsoleCursorInfo", SetLastError=true, CharSet=CharSet.Unicode)]
566 extern static bool GetConsoleCursorInfo (IntPtr handle, out ConsoleCursorInfo info);
568 [DllImport ("kernel32.dll", EntryPoint="SetConsoleCursorInfo", SetLastError=true, CharSet=CharSet.Unicode)]
569 extern static bool SetConsoleCursorInfo (IntPtr handle, ref ConsoleCursorInfo info);
571 [DllImport ("user32.dll", EntryPoint="GetKeyState", SetLastError=true, CharSet=CharSet.Unicode)]
572 extern static short GetKeyState (int virtKey);
574 [DllImport ("kernel32.dll", EntryPoint="GetConsoleMode", SetLastError=true, CharSet=CharSet.Unicode)]
575 extern static bool GetConsoleMode (IntPtr handle, out int mode);
577 [DllImport ("kernel32.dll", EntryPoint="SetConsoleMode", SetLastError=true, CharSet=CharSet.Unicode)]
578 extern static bool SetConsoleMode (IntPtr handle, int mode);
580 [DllImport ("kernel32.dll", EntryPoint="PeekConsoleInput", SetLastError=true, CharSet=CharSet.Unicode)]
581 extern static bool PeekConsoleInput (IntPtr handle, out InputRecord record, int length, out int eventsRead);
583 [DllImport ("kernel32.dll", EntryPoint="ReadConsoleInput", SetLastError=true, CharSet=CharSet.Unicode)]
584 extern static bool ReadConsoleInput (IntPtr handle, out InputRecord record, int length, out int nread);
586 [DllImport ("kernel32.dll", EntryPoint="GetLargestConsoleWindowSize", SetLastError=true, CharSet=CharSet.Unicode)]
587 extern static Coord GetLargestConsoleWindowSize (IntPtr handle);
589 [DllImport ("kernel32.dll", EntryPoint="ReadConsoleOutput", SetLastError=true, CharSet=CharSet.Unicode)]
590 extern static bool ReadConsoleOutput (IntPtr handle, void *buffer, Coord bsize, Coord bpos, ref SmallRect region);
592 [DllImport ("kernel32.dll", EntryPoint="WriteConsoleOutput", SetLastError=true, CharSet=CharSet.Unicode)]
593 extern static bool WriteConsoleOutput (IntPtr handle, CharInfo [] buffer, Coord bsize, Coord bpos, ref SmallRect region);