fenestroj 0.0.11

Easier wrappers for Win32 API stuff, safe when possible
Documentation
#![cfg(feature = "processenv")]

//! Manipulate properties of processes running on the machine.

use super::*;

use winapi::um::processenv::{GetStdHandle, SetStdHandle};

/// The the standard handles of a process.
///
/// For use with [`get_std_handle`](get_std_handle) and
/// [`set_std_handle`](set_std_handle)
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(u32)]
pub enum StdHandle {
  /// The standard input device.
  ///
  /// Initially, this is the console input buffer, `CONIN$`.
  Input = winapi::um::winbase::STD_INPUT_HANDLE,
  /// The standard output device.
  ///
  /// Initially, this is the active console screen buffer, `CONOUT$`.
  Output = winapi::um::winbase::STD_OUTPUT_HANDLE,
  /// The standard error device.
  ///
  /// Initially, this is the active console screen buffer, `CONOUT$`.
  Error = winapi::um::winbase::STD_ERROR_HANDLE,
}

/// Obtains one of the process's standard handles.
///
/// * Note that the handle returned on success can still be the `NULL` handle.
///
/// See
/// [`GetStdHandle`](https://docs.microsoft.com/en-us/windows/console/getstdhandle)
#[inline]
pub fn get_std_handle(std_handle: StdHandle) -> Result<HANDLE, ErrorCode> {
  let handle = unsafe { GetStdHandle(std_handle as u32) };
  if handle != INVALID_HANDLE_VALUE {
    Ok(handle)
  } else {
    Err(get_last_error())
  }
}

/// Sets one of the process's standard handles.
///
/// See
/// [`SetStdHandle`](https://docs.microsoft.com/en-us/windows/console/setstdhandle)
#[inline]
pub unsafe fn set_std_handle(
  std_handle: StdHandle,
  handle: HANDLE,
) -> Result<(), ErrorCode> {
  if SetStdHandle(std_handle as u32, handle) != 0 {
    Ok(())
  } else {
    Err(get_last_error())
  }
}