Struct win32console::console::WinConsole[][src]

pub struct WinConsole(_);
Expand description

Provides an access to the windows console of the current process and provides methods for interact with it.

Example

use win32console::console::WinConsole;

WinConsole::output().write_utf8("What's your name?".as_bytes()).unwrap();
let name = WinConsole::input().read_string().unwrap();
WinConsole::output().write_utf8(format!("Oh, Hello {}!", name.trim()).as_ref()).unwrap();

Implementations

Gets the specified handle by type.

Wraps a call to GetStdHandle.

Example
use win32console::console::{WinConsole, HandleType};
let input = WinConsole::get_std_handle(HandleType::Input).unwrap();

Sets the specified handle by type.

Wraps a call to SetStdHandle.

Example
use win32console::console::{WinConsole, HandleType};
let input = WinConsole::get_std_handle(HandleType::Input).unwrap();
WinConsole::set_std_handle(HandleType::Input, input);

Creates a Handle to the standard input file CONIN$, if the input is being redirected the value returned by get_std_handle cannot be used in functions that requires the console handle, but the returned Handle of this method can be used even if the input is being redirected.

More info about console handles: https://docs.microsoft.com/en-us/windows/console/console-handles

Wraps a call to CreateFileW.

Example
use win32console::console::WinConsole;
let handle = WinConsole::get_current_input_handle().unwrap();

Creates a Handle to the standard output file CONOUT$, if the input is being redirected the value returned by get_std_handle cannot be used in functions that requires the console handle, but the returned Handle of this method can be used even if the output is being redirected.

More info about console handles: https://docs.microsoft.com/en-us/windows/console/console-handles

Wraps a call to CreateFileW.

Example
use win32console::console::WinConsole;
let handle = WinConsole::get_current_output_handle().unwrap();

Gets a console with the STD_INPUT_HANDLE.

Example
use win32console::console::WinConsole;
let console = WinConsole::input();

Gets a console with the STD_OUTPUT_HANDLE.

Example
use win32console::console::WinConsole;
let console = WinConsole::output();

Gets a console with the STD_ERROR_HANDLE.

Example
use win32console::console::WinConsole;
let console = WinConsole::error();

Gets a console with current input handle. The handle will be always the current input handle even is the input is being redirected.

Example
use win32console::console::WinConsole;
let console = WinConsole::current_input();

Gets a console with the current output handle. The handle will be always the current input handle even is the output is being redirected.

Example
use win32console::console::WinConsole;
let console = WinConsole::current_output();

Gets a console with the given handle.

Example
use win32console::console::{WinConsole, HandleType};
let handle = WinConsole::get_std_handle(HandleType::Input).unwrap();
let console = WinConsole::with_handle(handle);

Allocates a new console for the calling process.

Errors
  • If the calling process have a console attached, free_console should be called first.

Wraps a call to AllocConsole.

Attaches the calling process to the console of the specified process.

  • proccess_id: The identifier of the process whose console is to be used. This parameter can be one of the following values:
  • pid: Use the console of the specified process.
  • ATTACH_PARENT_PROCESS (0xFFFFFFFF): Use the console of the parent of the current process.

Wraps a call to AttachConsole.

Errors
  • If the calling process is already attached to a console.
  • If the specified process does not have a console.
  • If the specified process does not exist.

Detaches the calling process from its console.

Wraps a call to FreeConsole.

Errors
  • If the calling process is not already attached to a console.

Sets the title of the current console.

Wraps a call to SetConsoleTitle.

Errors
  • No documented errors.
Example
use win32console::console::WinConsole;
use win32console::structs::input_record::InputRecord::KeyEvent;

// Either `output` or `input` handle can be used
WinConsole::set_title("Cool App!").unwrap();
let title = WinConsole::get_title().unwrap();
WinConsole::output().write_utf8(title.as_bytes()); // Cool App!

loop {
// We need a loop to see the title, when the process end the console will go back
// to the original title
if let KeyEvent(e) = WinConsole::input().read_single_input().unwrap() {
    // when press escape, exit
    // https://docs.microsoft.com/en-us/windows/win32/inputdev/virtual-key-codes
    if e.virtual_key_code == 0x1B {
        break;
    }
  }
}

Gets the title of the current console.

Wraps a call to GetConsoleTitle.

Errors
  • No documented errors.
Example
use win32console::console::WinConsole;
use win32console::structs::input_record::InputRecord::KeyEvent;

// Either `output` or `input` handle can be used
WinConsole::set_title("Cool App!").unwrap();
let title = WinConsole::get_title().unwrap();
WinConsole::output().write_utf8(title.as_bytes()); // Cool App!

loop {
// We need a loop to see the title, when the process end the console will go back
// to the original title
if let KeyEvent(e) = WinConsole::input().read_single_input().unwrap() {
    // when press escape, exit
    // https://docs.microsoft.com/en-us/windows/win32/inputdev/virtual-key-codes
    if e.virtual_key_code == 0x1B {
        break;
    }
  }
}

Retrieves the original title for the current console window.

Wraps a call to GetConsoleOriginalTitleW.

Errors
  • If f the buffer is not large enough to store the title.
Example
use win32console::console::WinConsole;
let title = WinConsole::get_original_title().unwrap();
WinConsole::output().write_utf8(title.as_bytes());

Gets the input code page used by the console associated with the calling process. A console uses its input code page to translate keyboard input into the corresponding character value.

See code pages: [https://docs.microsoft.com/en-us/windows/win32/intl/code-page-identifiers]

Wraps a call to GetConsoleCP.

Gets the output code page used by the console associated with the calling process. A console uses its output code page to translate the character values written by the various output functions into the images displayed in the console window.

See code pages: [https://docs.microsoft.com/en-us/windows/win32/intl/code-page-identifiers]

Wraps a call to GetConsoleOutputCP.

Sets the input code page used by the console associated with the calling process. A console uses its input code page to translate keyboard input into the corresponding character value.

Wraps a call to SetConsoleCP.

Sets the output code page used by the console associated with the calling process. A console uses its output code page to translate the character values written by the various output functions into the images displayed in the console window.

Wraps a call to SetConsoleOutputCP.

Retrieves the display mode of the current console.

Wraps a call to GetConsoleDisplayMode.

Gets information about the current console selection.

Wraps a call to GetConsoleSelectionInfo.

Example
use win32console::console::WinConsole;
let info = WinConsole::get_selection_info().unwrap();

Creates a new console screen buffer with:

  • dwDesiredAccess = GENERIC_READ | GENERIC_WRITE`
  • dwShareMode = FILE_SHARE_READ | FILE_SHARE_WRITE

Wraps a call to CreateConsoleScreenBuffer.

Example
use win32console::console::{WinConsole, HandleType};
use std::time::Duration;

let std_output_handle = WinConsole::get_std_handle(HandleType::Output).unwrap();
let new_handle = WinConsole::create_console_screen_buffer().unwrap();

assert!(std_output_handle.is_valid());
assert!(new_handle.is_valid());

// Write to the new handle
WinConsole::with_handle(new_handle).write_utf8("Hola amigos!".as_bytes());

// Write to the std output handle
WinConsole::with_handle(std_output_handle).write_utf8("Hello Friends!".as_bytes());

// Sets a new active screen buffer to display the message
WinConsole::set_active_console_screen_buffer(&new_handle);
// Keep the message visible for 3 secs
std::thread::sleep(Duration::from_secs(3));
// Restore the std output handle
WinConsole::set_active_console_screen_buffer(&std_output_handle);

Creates a new console screen buffer with the given options.

Sets the specified screen buffer to be the currently displayed console screen buffer.

Wraps a call to SetConsoleActiveScreenBuffer.

Retrieves a list of the processes attached to the current console.

Wraps a call to GetConsoleProcessList.

Errors
  • No documented errors.
Example
use win32console::console::WinConsole;
let process_id = WinConsole::get_process_list().unwrap();
for pid in &process_id{
    WinConsole::output().write_utf8(format!("{}", pid).as_bytes()).unwrap();
}

Sets the history settings for the calling process’s console.

Wraps a call to SetConsoleHistoryInfo.

Errors
  • If the calling process is not a console process, the function fails and sets the last error code to ERROR_ACCESS_DENIED.
Example
use win32console::console::WinConsole;
let mut  info = WinConsole::get_history_info().unwrap();
info.allow_duplicate_entries = false;
WinConsole::set_history_info(info).unwrap();

Retrieves the history settings for the calling process’s console.

Wraps a call to GetConsoleHistoryInfo.

Errors
  • No documented errors.
Example
use win32console::console::WinConsole;
let mut  info = WinConsole::get_history_info().unwrap();
info.allow_duplicate_entries = false;
WinConsole::set_history_info(info).unwrap();

Retrieves the window handle used by the console associated with the calling process. The return value is a Some(Handle) to the window used by the console associated with the calling process or None if there is no such associated console.

Wraps a call to GetConsoleWindow.

Example
use win32console::console::WinConsole;
let handle = WinConsole::get_window().unwrap();
assert!(!handle.is_null());

Gets the current console mode.

Remarks

The method get_display_mode don’t provide the actual mode of the console which is set by set_display_mode, this method use the current console window handle to check if the windows is fullscreen or windowed.

Example
use win32console::console::{WinConsole, DisplayMode};
let mode = WinConsole::get_actual_display_mode().unwrap();
if mode == DisplayMode::FullScreen{
    WinConsole::output().write_utf8("Is fullscreen".as_bytes()).unwrap();
}
else{
    WinConsole::output().write_utf8("Is windowed".as_bytes()).unwrap();
}

Gets the handle used for this console, which will be provided by the handle_provider.

Gets the current mode of the console

Wraps a call to GetConsoleMode.

Errors
  • No documented errors.
Example
use win32console::console::{WinConsole, ConsoleMode};

let old_mode = WinConsole::input().get_mode().unwrap();
let new_mode = ConsoleMode::ENABLE_PROCESSED_INPUT | ConsoleMode::ENABLE_LINE_INPUT;
// We change the input mode so the characters are not displayed
WinConsole::input().set_mode(new_mode);

let value = WinConsole::input().read_string().unwrap(); // Don't will be displayed due new mode
WinConsole::output().write_utf8(value.as_bytes());
WinConsole::input().set_mode(old_mode); // Reset the mode

Sets the current mode of the console

Wraps a call to GetConsoleMode.

Errors
  • No documented errors.
Example
use win32console::console::{WinConsole, ConsoleMode};

let old_mode = WinConsole::input().get_mode().unwrap();
let new_mode = ConsoleMode::ENABLE_PROCESSED_INPUT | ConsoleMode::ENABLE_LINE_INPUT;
// We change the input mode so the characters are not displayed
WinConsole::input().set_mode(new_mode);

let value = WinConsole::input().read_string().unwrap(); // Don't will be displayed due new mode
WinConsole::output().write_utf8(value.as_bytes());
WinConsole::input().set_mode(old_mode); // Reset the mode

Checks if the console have the specified mode.

Errors
  • No documented errors.
Example
use win32console::console::{WinConsole, ConsoleMode};
assert!(WinConsole::input().has_mode(ConsoleMode::ENABLE_PROCESSED_INPUT).unwrap());

Sets the display mode of the specified console screen buffer and returns the new dimensions of the console buffer.

Wraps a call to SetConsoleDisplayMode.

Errors
  • If the handle is an invalid handle or an input handle: WinConsole::input(), the function should be called using WinConsole::output() or a valid output handle.
Example
use win32console::console::{WinConsole, DisplayMode};
WinConsole::output().set_display_mode(DisplayMode::FullScreen)
                    .expect("Cannot change to fullscreen");

Sets extended information about the console font. This function change the font into of all the current values in the console.

Wraps a call to SetCurrentConsoleFontEx.

Errors
  • If the handle is an invalid handle or an input handle: WinConsole::input(), the function should be called using WinConsole::output() or a valid output handle.
Example
use win32console::console::WinConsole;

let old_info = WinConsole::output().get_font_ex(false).unwrap();
let mut new_info = old_info;
new_info.font_weight = 800; //Bold font
WinConsole::output().set_font_info_ex(new_info, false).unwrap();
WinConsole::output().write_utf8("Hello World".as_bytes()).unwrap();

//  WinConsole::output().set_console_font_info(old_info).unwrap();
// DON'T WILL SHOW BOTH `BOLD` AND `NORMAL` FONT!!

// If we try to restore the old_info the new changes don't will be visible due
// this method changes the font info of all the characters being displayed in the console

If changes are not visibles in your current IDE try to execute directly the .exe in the folder.

Gets information about the console font.

Wraps a call to GetCurrentConsoleFont.

Errors
  • If the handle is an invalid handle or an input handle: WinConsole::input(), the function should be called using WinConsole::output() or a valid output handle.
Example
use win32console::console::{WinConsole};
let info = WinConsole::output().get_font(true).unwrap();

Gets extended information about the console font.

Wraps a call to GetCurrentConsoleFontEx.

Errors
  • If the handle is an invalid handle or an input handle: WinConsole::input(), the function should be called using WinConsole::output() or a valid output handle.
Example
use win32console::console::WinConsole;

let old_info = WinConsole::output().get_font_ex(false).unwrap();
let mut new_info = old_info;
new_info.font_weight = 800; //Bold font
WinConsole::output().set_font_info_ex(new_info, false).unwrap();
WinConsole::output().write_utf8("Hello World".as_bytes()).unwrap();

Retrieves the size of the font used by the specified console screen buffer.

Wraps a call to GetConsoleFontSize.

Errors
  • If the handle is an invalid handle or an input handle: WinConsole::input(), the function should be called using WinConsole::output() or a valid output handle.
Example
use win32console::console::WinConsole;
let info = WinConsole::output().get_font(false).unwrap();
let font_size = WinConsole::output().get_font_size(info.font_index).unwrap();
WinConsole::output().write_utf8(format!("Font size: {}", font_size).as_bytes());

Gets the current screen buffer info.

Errors
  • If the handle is an invalid handle or an input handle: WinConsole::input(), the function should be called using WinConsole::output() or a valid output handle.

Wraps a call to GetConsoleScreenBufferInfo.

use win32console::console::{WinConsole, ConsoleTextAttribute};
let info = WinConsole::output().get_screen_buffer_info().unwrap();

Gets extended information of the console screen buffer.

Wraps a call to GetConsoleScreenBufferInfoEx.

Errors
  • If the handle is an invalid handle or an input handle: WinConsole::input(), the function should be called using WinConsole::output() or a valid output handle.
Example
use win32console::console::{WinConsole, ConsoleTextAttribute};

let old_info = WinConsole::output().get_screen_buffer_info_ex().unwrap();
let mut  new_info = old_info.clone();
new_info.attributes = ConsoleTextAttribute::FOREGROUND_RED | ConsoleTextAttribute::FOREGROUND_INTENSITY;
WinConsole::output().set_screen_buffer_info_ex(new_info); // Set foreground color red
WinConsole::output().write_utf8("Hello World!".as_bytes());
WinConsole::output().set_screen_buffer_info_ex(old_info); // Restore old info

Sets the extended console screen buffer information.

Wraps a call to SetConsoleScreenBufferInfoEx.

Errors
  • If the handle is an invalid handle or an input handle: WinConsole::input(), the function should be called using WinConsole::output() or a valid output handle.
Example
use win32console::console::{WinConsole, ConsoleTextAttribute};

let old_info = WinConsole::output().get_screen_buffer_info_ex().unwrap();
let mut  new_info = old_info.clone();
new_info.attributes = ConsoleTextAttribute::FOREGROUND_RED | ConsoleTextAttribute::FOREGROUND_INTENSITY;
WinConsole::output().set_screen_buffer_info_ex(new_info); // Set foreground color red
WinConsole::output().write_utf8("Hello World!".as_bytes());
WinConsole::output().set_screen_buffer_info_ex(old_info); // Restore old info

Set the size of the console screen buffer.

Wraps a call to SetConsoleScreenBufferSize.

Errors
  • If the handle is an invalid handle or an input handle: WinConsole::input(), the function should be called using WinConsole::output() or a valid output handle.
Example
use win32console::console::WinConsole;
use win32console::structs::coord::Coord;
const WIDTH : i16 = 30;
const HEIGHT : i16 = 40;

WinConsole::output().set_screen_buffer_size(Coord::new(WIDTH, HEIGHT));

Sets the current size and position of the console screen buffer window.

  • absolute: If this parameter is TRUE, the coordinates specify the new upper-left and lower-right corners of the window. If it is FALSE, the coordinates are relative to the current window-corner coordinates.
  • window: specifies the new upper-left and lower-right corners of the window.

Wraps a call to SetConsoleWindowInfo.

Remarks
  • The function may return an error when using the console of an IDE.
Errors
  • If the handle is an invalid handle or an input handle: WinConsole::input(), the function should be called using WinConsole::output() or a valid output handle.
  • If the window parameter is too big.
Example
use win32console::console::WinConsole;
use win32console::structs::small_rect::SmallRect;
let window = SmallRect::new(0, 0, 40, 50);
WinConsole::output().set_window_info(true, &window);

Sets the position of the cursor. don’t confuse with mouse cursor.

Wraps a call to SetConsoleCursorPosition.

Errors
  • If the handle is an invalid handle or an input handle: WinConsole::input(), the function should be called using WinConsole::output() or a valid output handle.
Example
use win32console::console::WinConsole;
use win32console::structs::input_record::InputRecord::KeyEvent;

fn remove_last(){
       let pos = WinConsole::output().get_cursor_position().unwrap();
       if pos.x > 0{
           const WHITE_SPACE : &[u8; 1] = b" ";
           let new_pos = pos.with_x(pos.x - 1);

           // Move back, write a whitespace and move back again
           // to remove the last written char
           WinConsole::output().set_cursor_position(new_pos);
           WinConsole::output().write_utf8(WHITE_SPACE);
           WinConsole::output().set_cursor_position(new_pos);
       }
   }

   // A simple alphanumeric reader from the std input
   loop{
       if let KeyEvent(event) = WinConsole::input().read_single_input().unwrap(){
            // Only enter when the key is pressed down
           if event.key_down{
               // Only alphanumeric are allowed so any other is ignore
               if event.u_char.is_ascii_alphanumeric() {
                   let mut buf = [0];
                   event.u_char.encode_utf8(&mut buf);
                   // Write the character
                   WinConsole::output().write_utf8(&buf);
               }
               else{
                   match event.virtual_key_code{
                       0x08 => { remove_last(); } // Remove last on backspace press
                       0x1B => { break; }         // Exit when escape is press
                       _ => {}
                   }
               }
           }
       }
   }

Gets the current position of the cursor. don’t confuse with mouse cursor.

Errors
  • If the handle is an invalid handle or an input handle: WinConsole::input(), the function should be called using WinConsole::output() or a valid output handle.
Example
use win32console::console::WinConsole;
use win32console::structs::input_record::InputRecord::KeyEvent;

fn remove_last(){
       let pos = WinConsole::output().get_cursor_position().unwrap();
       if pos.x > 0{
           const WHITE_SPACE : &[u8; 1] = b" ";
           let new_pos = pos.with_x(pos.x - 1);

           // Move back, write a whitespace and move back again
           // to remove the last written char
           WinConsole::output().set_cursor_position(new_pos);
           WinConsole::output().write_utf8(WHITE_SPACE);
           WinConsole::output().set_cursor_position(new_pos);
       }
   }

   // A simple alphanumeric reader from the std input
   loop{
       if let KeyEvent(event) = WinConsole::input().read_single_input().unwrap(){
            // Only enter when the key is pressed down
           if event.key_down{
               // Only alphanumeric are allowed so any other is ignore
               if event.u_char.is_ascii_alphanumeric() {
                   let mut buf = [0];
                   event.u_char.encode_utf8(&mut buf);
                   // Write the character
                   WinConsole::output().write_utf8(&buf);
               }
               else{
                   match event.virtual_key_code{
                       0x08 => { remove_last(); } // Remove last on backspace press
                       0x1B => { break; }         // Exit when escape is press
                       _ => {}
                   }
               }
           }
       }
   }

Retrieves information about the size and visibility of the cursor for the specified console screen buffer.

Wraps a call to GetConsoleCursorInfo.

Errors
  • If the handle is an invalid handle or an input handle: WinConsole::input(), the function should be called using WinConsole::output() or a valid output handle.
Example
use win32console::console::WinConsole;
let cursor_info = WinConsole::output().get_cursor_info();

Clears the content of the console screen buffer and set the cursor to (0, 0)

Errors
  • No documented errors.
Example
use win32console::console::WinConsole;
WinConsole::output().clear();

Fills the content of the console with the specified char.

Wraps a call to FillConsoleOutputCharacterW.

Errors
  • If the handle is an invalid handle or an input handle: WinConsole::input(), the function should be called using WinConsole::output() or a valid output handle.
Example
use win32console::console::WinConsole;
let current_pos = WinConsole::output().get_cursor_position().unwrap();
WinConsole::output().fill_with_char(current_pos, 10, 'x').unwrap();

Fills the content of the console with the specified attribute.

Wraps a call to FillConsoleOutputAttribute.

Errors
  • If the handle is an invalid handle or an input handle: WinConsole::input(), the function should be called using WinConsole::output() or a valid output handle.
Example
use win32console::console::WinConsole;
let len = 100;
let current_pos = WinConsole::output().get_cursor_position().unwrap();
WinConsole::output().fill_with_char(current_pos, len, ' ').unwrap();

for i in 0..len{
   let mut pos = current_pos.clone();
   pos.x += i as i16;
   let color : u16 = (16 << (i % 3)) as u16; // Apply colors to the characters
   WinConsole::output().fill_with_attribute(pos, 1, color);
}

Sets the text attribute of the characters in the console.

  • attribute: the attributes to use, those attributes can be access using ConsoleTextAttribute struct.

Wraps a call to SetConsoleTextAttribute.

Errors
  • If the handle is an invalid handle or an input handle: WinConsole::input(), the function should be called using WinConsole::output() or a valid output handle.
Example
use win32console::console::{WinConsole, ConsoleTextAttribute};

let old_attributes = WinConsole::output().get_text_attribute().unwrap();
let new_attributes = ConsoleTextAttribute::BACKGROUND_BLUE;

WinConsole::output().set_text_attribute(new_attributes);
WinConsole::output().write_utf8("Hello World!".as_bytes());
WinConsole::output().set_text_attribute(old_attributes);

Gets the text attributes of the characters in the console.

Errors
  • If the handle is an invalid handle or an input handle: WinConsole::input(), the function should be called using WinConsole::output() or a valid output handle.
Example
use win32console::console::{WinConsole, ConsoleTextAttribute};

let old_attributes = WinConsole::output().get_text_attribute().unwrap();
let new_attributes = ConsoleTextAttribute::BACKGROUND_BLUE;

WinConsole::output().set_text_attribute(new_attributes);
WinConsole::output().write_utf8("Hello World!".as_bytes());
WinConsole::output().set_text_attribute(old_attributes);

Gets the largest size the console window can get.

Wraps a call to GetLargestConsoleWindowSize.

Errors
  • If the handle is an invalid handle or an input handle: WinConsole::input(), the function should be called using WinConsole::output() or a valid output handle.
Example
use win32console::console::WinConsole;
let max_size = WinConsole::output().get_largest_window_size().unwrap();

Gets the number of unread input events.

Wraps a call to GetNumberOfConsoleInputEvents.

Errors
  • If the handle is an invalid handle or an output handle: WinConsole::output(), the function should be called using WinConsole::input() or a valid input handle.
Example
use win32console::console::WinConsole;
let unread_events = WinConsole::input().get_number_of_input_events().unwrap();

Gets the number of mouse buttons used for the mouse available for this console.

Wraps a call to GetNumberOfConsoleMouseButtons.

Errors
  • No documented errors.
Example
use win32console::console::WinConsole;
let x = WinConsole::input().get_number_of_mouse_buttons().unwrap();
let y = WinConsole::output().get_number_of_mouse_buttons().unwrap();
assert_eq!(x, y);

Moves a block of data in a screen buffer. The effects of the move can be limited by specifying a clipping rectangle, so the contents of the console screen buffer outside the clipping rectangle are unchanged.

Wraps a call to ScrollConsoleScreenBufferW.

Errors
  • No documented errors.

Reads a single event from the console.

Errors
  • If the handle is an invalid handle or an output handle: WinConsole::output(), the function should be called using WinConsole::input() or a valid input handle.
Example
use win32console::structs::input_record::InputRecord::KeyEvent;
use win32console::console::WinConsole;

loop{
       // A simple alphanumeric reader from the std input
       if let KeyEvent(event) = WinConsole::input().read_single_input().unwrap(){
            // Only enter when the key is pressed down
           if event.key_down{
               // Only alphanumeric are allowed so any other is ignore
               if !(event.u_char.is_ascii_alphanumeric()) {
                   match event.virtual_key_code{
                       0x1B => { break; }         // Exit when escape is press
                       _ => {}
                   }
               }
                else {
                   let mut buf = [0];
                   event.u_char.encode_utf8(&mut buf);
                   // Write the character
                   WinConsole::output().write_utf8(&buf);
                }
           }
       }
   }

Reads input events from the console.

  • buffer_size: the size of the buffer that will store the events.
Errors
  • If the handle is an invalid handle or an output handle: WinConsole::output(), the function should be called using WinConsole::input() or a valid input handle.
Example
use win32console::console::WinConsole;
use win32console::structs::input_record::InputRecord::KeyEvent;
let input_records = WinConsole::input().read_input_n(10).unwrap();

let mut buf = String::new();
for record in input_records{
    if let KeyEvent(key) = record{
        if key.key_down && key.u_char.is_ascii_alphanumeric(){
            buf.push(key.u_char);
        }
    }
}

WinConsole::output().write_utf8(buf.as_bytes());

Fills the specified buffer with InputRecord from the console.

Wraps a call to ReadConsoleInputW.

Returns

The number of input events read.

Errors
  • If the handle is an invalid handle or an output handle: WinConsole::output(), the function should be called using WinConsole::input() or a valid input handle.
Example
use std::mem::MaybeUninit;
use win32console::structs::input_record::InputRecord;
use win32console::console::WinConsole;
use win32console::structs::input_record::InputRecord::KeyEvent;

let mut input_records : [InputRecord; 10] = unsafe { MaybeUninit::zeroed().assume_init() };
WinConsole::input().read_input(&mut input_records).unwrap();

let mut buf = String::new();
for record in input_records.iter(){
    if let KeyEvent(key) = record{
        if key.key_down && key.u_char.is_ascii_alphanumeric(){
            buf.push(key.u_char);
        }
    }
}

WinConsole::output().write_utf8(buf.as_bytes());

Reads character and color attribute data from a rectangular block of character cells in a console screen buffer, and the function writes the data to a rectangular block at a specified location in the destination buffer.

Wraps a call to ReadConsoleOutputW.

Copies a specified number of character attributes from consecutive cells of a console screen buffer, beginning at a specified location.

Wraps a call to ReadConsoleOutputAttribute.

Returns

The number of attributes read.

Errors
  • If the handle is an invalid handle or an output handle: WinConsole::output(), the function should be called using WinConsole::input() or a valid input handle.
Example
use win32console::console::{WinConsole, ConsoleTextAttribute};
use win32console::structs::console_color::ConsoleColor;
use win32console::structs::coord::Coord;

fn write_color(data: &str, color: ConsoleColor){
    let c = WinConsole::output().get_foreground_color().unwrap();
    WinConsole::output().set_foreground_color(color);
    WinConsole::output().write_utf8(data.as_bytes());
    WinConsole::output().set_foreground_color(c);
}

WinConsole::output().clear();
write_color("R", ConsoleColor::DarkRed);
write_color("G", ConsoleColor::DarkGreen);
write_color("B", ConsoleColor::DarkBlue);

let mut buf = [0u16, 0u16, 0u16];
let attributes_read = WinConsole::output().read_output_attribute(&mut buf, Coord::ZERO).unwrap();

assert_eq!(3, attributes_read);
assert_eq!(ConsoleTextAttribute::FOREGROUND_RED, buf[0]);
assert_eq!(ConsoleTextAttribute::FOREGROUND_GREEN, buf[1]);
assert_eq!(ConsoleTextAttribute::FOREGROUND_BLUE, buf[2]);

Copies a number of characters from consecutive cells of a console screen buffer, beginning at a specified location.

Wraps a call to ReadConsoleOutputCharacterW.

Returns

The number of characters read.

Errors
  • If the handle is an invalid handle or an output handle: WinConsole::output(), the function should be called using WinConsole::input() or a valid input handle.
use win32console::console::WinConsole;
use win32console::structs::coord::Coord;

WinConsole::output().clear();

let data = b"Hola Mundo";
WinConsole::output().write_utf8(data);
let mut buf = vec![u8::default(); data.len()];
let chars_read = WinConsole::output().read_output_character(&mut buf, Coord::ZERO).expect("Unable to read");

assert_eq!(chars_read, data.len());
assert_eq!(data, buf.as_slice());

Fills the specified buffer with the unread InputRecord from the console.

Returns

The number of input events read.

Errors
  • If the handle is an invalid handle or an output handle: WinConsole::output(), the function should be called using WinConsole::input() or a valid input handle.

Wraps a call to PeekConsoleInputW.

Example
use std::mem::MaybeUninit;
use win32console::structs::input_record::InputRecord;
use win32console::console::WinConsole;
use win32console::structs::input_record::InputRecord::KeyEvent;

let mut input_records : [InputRecord; 10] = unsafe { MaybeUninit::zeroed().assume_init() };
WinConsole::input().peek_input(&mut input_records).unwrap();

let mut buf = String::new();
for record in input_records.iter(){
    if let KeyEvent(key) = record{
        if key.key_down && key.u_char.is_ascii_alphanumeric(){
            buf.push(key.u_char);
        }
    }
}

WinConsole::output().write_utf8(buf.as_bytes());

Reads a String from the standard input, followed by a newline.

Errors
  • If the handle is an invalid handle or an output handle: WinConsole::output(), the function should be called using WinConsole::input() or a valid input handle.
Example
use win32console::console::WinConsole;

WinConsole::output().write_utf8("What's your name? ".as_bytes());
let value = WinConsole::input().read_string().unwrap();
WinConsole::output().write_utf8(format!("Hello {}", value).as_bytes());

Fills the given u8 buffer with characters from the standard input.

Returns

The number of characters read.

Errors
  • If the handle is an invalid handle or an output handle: WinConsole::output(), the function should be called using WinConsole::input() or a valid input handle.
Example
use std::mem::MaybeUninit;
use win32console::console::WinConsole;
let mut buffer : [u8 ; 10] = unsafe { MaybeUninit::zeroed().assume_init() };
WinConsole::input().read_utf8(&mut buffer);

Fills the given u16 buffer with characters from the standard input.

Wraps a call to ReadConsoleW.

Returns

The number of characters read.

Errors
  • If the handle is an invalid handle or an output handle: WinConsole::output(), the function should be called using WinConsole::input() or a valid input handle.
Example
use std::mem::MaybeUninit;
use win32console::console::WinConsole;
let mut buffer : [u16 ; 10] = unsafe { MaybeUninit::zeroed().assume_init() };
WinConsole::input().read_utf16(&mut buffer);

Fills the given u8 buffer with characters from the standard input using the specified console read control.

  • control: provides information used for a read operation as the number of chars to skip or the end signal.

Wraps a call to ReadConsoleA.

Returns

The number of characters read.

Errors
  • If the handle is an invalid handle or an output handle: WinConsole::output(), the function should be called using WinConsole::input() or a valid input handle.
Example
use std::mem::MaybeUninit;
use win32console::console::WinConsole;
use win32console::structs::console_read_control::ConsoleReadControl;

const CTRL_Z: u8 = 26;
const CTRL_Z_MASK: u32 = (1 << CTRL_Z) as u32;

let control = ConsoleReadControl::new_with_mask(CTRL_Z_MASK);
let mut buffer : [u8 ; 32] = unsafe { MaybeUninit::zeroed().assume_init() };
let mut len = WinConsole::input().read_utf8_with_control(&mut buffer, control).unwrap();

// If the last character is the control signal we ignore it.
if len > 0 && buffer[len - 1] == CTRL_Z{
    len -= 1;
}

let string = String::from_utf8_lossy(&buffer[..len])
                    .trim() // String terminated in newline
                    .to_string();

// buffer is terminated in '\r\n', assertion will fail when write 32 characters
assert_eq!(len - 2, string.len());
WinConsole::output().write_utf8(string.as_bytes());

Fills the given u16 buffer with characters from the standard input using the specified console read control.

  • control: provides information used for a read operation as the number of chars to skip or the end signal.

Wraps a call to ReadConsoleW.

Returns

The number of characters read.

Errors
  • If the handle is an invalid handle or an output handle: WinConsole::output(), the function should be called using WinConsole::input() or a valid input handle.
Example
use std::mem::MaybeUninit;
use win32console::console::WinConsole;
use win32console::structs::console_read_control::ConsoleReadControl;

const CTRL_Z: u16 = 26;
const CTRL_Z_MASK: u32 = (1 << CTRL_Z) as u32;

let control = ConsoleReadControl::new_with_mask(CTRL_Z_MASK);
let mut buffer : [u16 ; 32] = unsafe { MaybeUninit::zeroed().assume_init() };
let mut len = WinConsole::input().read_utf16_with_control(&mut buffer, control).unwrap();

// If the last character is the control signal we ignore it.
if len > 0 && buffer[len - 1] == CTRL_Z{
    len -= 1;
}

let string = String::from_utf16_lossy(&buffer[..len])
                    .trim() // String terminated in newline
                    .to_string();

// buffer is terminated in '\r\n', assertion will fail when write 32 characters
assert_eq!(len - 2, string.len());
WinConsole::output().write_utf8(string.as_bytes());

Flushes the console input buffer. All input records currently in the input buffer are discarded.

Wraps a call to FlushConsoleInputBuffer.

Errors
  • If the handle is an invalid handle or an output handle: WinConsole::output(), the function should be called using WinConsole::input() or a valid input handle.
Example
use win32console::console::WinConsole;
WinConsole::input().flush_input();

Writes the specified u8 buffer of chars in the current cursor position of the console.

Wraps a call to WriteConsoleA.

Returns

The number of characters written.

Errors
  • If the handle is an invalid handle or an input handle: WinConsole::input(), the function should be called using WinConsole::output() or a valid output handle.
Example
use win32console::console::WinConsole;
WinConsole::output().write_utf8("Hello World!".as_bytes());

Writes the specified buffer of chars in the current cursor position of the console.

Wraps a call to WriteConsoleW.

Returns

The number of characters written.

Errors
  • If the handle is an invalid handle or an input handle: WinConsole::input(), the function should be called using WinConsole::output() or a valid output handle.
Example
use win32console::console::WinConsole;
let x = "Hello World!".encode_utf16().collect::<Vec<u16>>();
WinConsole::output().write_utf16(x.as_slice());

Writes the given buffer of CharInfo into the screen buffer.

Wraps a call to WriteConsoleOutputW.

See also: [https://www.randygaul.net/2011/11/16/windows-console-game-writing-to-the-console/]

  • buffer_size: the size of the buffer in rows and columns.
  • buffer_start: the origin in the buffer where start to take the characters to write, typically (0,0).
  • write_area: Represents the screen buffer area to write to.
Remarks
  • This functions don’t affect the cursor position.
  • If the write_area is outside the screen buffer no data is written.
Errors
  • If the handle is an invalid handle or an input handle: WinConsole::input(), the function should be called using WinConsole::output() or a valid output handle.
Example
use win32console::structs::coord::Coord;
use win32console::console::WinConsole;
use win32console::structs::char_info::CharInfo;
use win32console::structs::small_rect::SmallRect;
const WIDTH : usize = 40;
const HEIGHT : usize = 30;

let mut buffer = Vec::with_capacity(WIDTH * HEIGHT);
let buffer_size = Coord::new(WIDTH as i16, HEIGHT as i16);
let window = SmallRect::new(0, 0, (WIDTH - 1) as i16, (HEIGHT - 1) as i16);

WinConsole::output().set_window_info(true, &window).unwrap();
WinConsole::output().set_screen_buffer_size(buffer_size.clone()).unwrap();

for i in 0..buffer.capacity(){
   let char_info = CharInfo::new(' ', (16 << i % 3) as u16);
    buffer.push(char_info);
}

WinConsole::output().write_output(buffer.as_ref(), buffer_size, Coord::ZERO, window).unwrap();

Writes data directly to the console input buffer.

Wraps a call to WriteConsoleInputA.

Errors
  • If the handle is an invalid handle or an output handle: WinConsole::output(), the function should be called using WinConsole::input() or a valid input handle.
Example
use win32console::structs::input_record::InputRecord;
use win32console::structs::input_event::{KeyEventRecord, ControlKeyState};
use win32console::structs::input_record::InputRecord::KeyEvent;
use win32console::console::WinConsole;
use winapi::_core::mem::MaybeUninit;

let mut key_event : KeyEventRecord = unsafe { std::mem::zeroed() };
key_event.repeat_count = 1;
key_event.control_key_state = ControlKeyState::new(0);
key_event.u_char = 'a';
key_event.key_down = true;
key_event.virtual_scan_code = 0;
key_event.virtual_key_code = 0x41;

// Discard all the records in the buffer
WinConsole::input().flush_input();

let record : [InputRecord; 1] = [KeyEvent(key_event)];
WinConsole::input().write_input(&record).expect("Cannot write the event");

let mut buf : [InputRecord; 1] = unsafe { MaybeUninit::zeroed().assume_init() };
WinConsole::input().peek_input(&mut buf).expect("Cannot peek the events");

assert_eq!(record, buf);

Copies a number of character attributes to consecutive cells of a console screen buffer, beginning at a specified location.

Wraps a call to WriteConsoleOutputAttribute.

Errors
  • If the handle is an invalid handle or an output handle: WinConsole::output(), the function should be called using WinConsole::input() or a valid input handle.
Examples
use win32console::console::{WinConsole, ConsoleTextAttribute};
use win32console::structs::coord::Coord;

WinConsole::output().clear();
WinConsole::output().write_utf8(b"RGB");

let attributes : [u16; 3] = [ConsoleTextAttribute::FOREGROUND_RED, ConsoleTextAttribute::FOREGROUND_GREEN, ConsoleTextAttribute::FOREGROUND_BLUE];
WinConsole::output().write_output_attribute(&attributes, Coord::ZERO);

Copies a number of characters to consecutive cells of a console screen buffer, beginning at a specified location.

Wraps a call to WriteConsoleOutputCharacterW.

Errors
  • If the handle is an invalid handle or an output handle: WinConsole::output(), the function should be called using WinConsole::input() or a valid input handle.
Example
use win32console::console::WinConsole;
use win32console::structs::coord::Coord;

WinConsole::output().clear();
WinConsole::output().write_utf8("*".repeat(15).as_bytes());
WinConsole::output().write_output_character(b"Hello", Coord::new(5, 0));

Gets the foreground color of the console.

Errors
  • If the handle is an invalid handle or an input handle: WinConsole::input(), the function should be called using WinConsole::output() or a valid output handle.
Example
use win32console::console::WinConsole;
use win32console::structs::console_color::ConsoleColor;
let fg = WinConsole::output().get_foreground_color().unwrap();
let bg = WinConsole::output().get_background_color().unwrap();

WinConsole::output().set_foreground_color(ConsoleColor::Red);
WinConsole::output().set_background_color(ConsoleColor::Yellow);
WinConsole::output().write_utf8("Hello World!".as_bytes());

// Restore colors
WinConsole::output().set_foreground_color(fg);
WinConsole::output().set_background_color(bg);

Gets the background color of the console.

Errors
  • If the handle is an invalid handle or an input handle: WinConsole::input(), the function should be called using WinConsole::output() or a valid output handle.
Example
use win32console::console::WinConsole;
use win32console::structs::console_color::ConsoleColor;
let fg = WinConsole::output().get_foreground_color().unwrap();
let bg = WinConsole::output().get_background_color().unwrap();

WinConsole::output().set_foreground_color(ConsoleColor::Black);
WinConsole::output().set_background_color(ConsoleColor::White);
WinConsole::output().write_utf8("Hello World!".as_bytes());

// Restore colors
WinConsole::output().set_foreground_color(fg);
WinConsole::output().set_background_color(bg);

Sets the foreground color of the console.

Errors
  • If the handle is an invalid handle or an input handle: WinConsole::input(), the function should be called using WinConsole::output() or a valid output handle.
Example
use win32console::console::WinConsole;
use win32console::structs::console_color::ConsoleColor;
let fg = WinConsole::output().get_foreground_color().unwrap();
let bg = WinConsole::output().get_background_color().unwrap();

WinConsole::output().set_foreground_color(ConsoleColor::Yellow);
WinConsole::output().set_background_color(ConsoleColor::DarkMagenta);
WinConsole::output().write_utf8("Hello World!".as_bytes());

// Restore colors
WinConsole::output().set_foreground_color(fg);
WinConsole::output().set_background_color(bg);

Sets the background color of the console.

Errors
  • If the handle is an invalid handle or an input handle: WinConsole::input(), the function should be called using WinConsole::output() or a valid output handle.
Example
use win32console::console::WinConsole;
use win32console::structs::console_color::ConsoleColor;
let fg = WinConsole::output().get_foreground_color().unwrap();
let bg = WinConsole::output().get_background_color().unwrap();

WinConsole::output().set_foreground_color(ConsoleColor::DarkBlue);
WinConsole::output().set_background_color(ConsoleColor::Green);
WinConsole::output().write_utf8("Hello World!".as_bytes());

// Restore colors
WinConsole::output().set_foreground_color(fg);
WinConsole::output().set_background_color(bg);

Generates simple tones on the speaker. The function is synchronous; it performs an alertable wait and does not return control to its caller until the sound finishes.

Wraps a call to Beep.

Example
use win32console::console::WinConsole;

// https://pages.mtu.edu/~suits/notefreqs.html
let musical_notes = [
   (2093, 500), (2349, 500), (2637, 500), (2793, 500),
   (3135, 500), (3520, 500), (3951, 500), (4186, 500)
];

for n in &musical_notes{
   WinConsole::beep(n.0, n.1).unwrap();
}

Trait Implementations

Returns a copy of the value. Read more

Performs copy-assignment from source. Read more

Formats the value using the given formatter. Read more

This method tests for self and other values to be equal, and is used by ==. Read more

This method tests for !=.

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

Immutably borrows from an owned value. Read more

Mutably borrows from an owned value. Read more

Performs the conversion.

Performs the conversion.

The resulting type after obtaining ownership.

Creates owned data from borrowed data, usually by cloning. Read more

🔬 This is a nightly-only experimental API. (toowned_clone_into)

recently added

Uses borrowed data to replace owned data, usually by cloning. Read more

The type returned in the event of a conversion error.

Performs the conversion.

The type returned in the event of a conversion error.

Performs the conversion.