How to send an alert about panic ( It is not Okay.) to user before closing command line window (terminal) ?
Here my axial solution. Is there a more elegant way ?
fn main() {
if ... {
println!( "Not found ... (Enter to Close)") ; // Need attention before closing
let mut my_msg = &mut String::new();
std::io::stdin().read_line( &mut my_msg) .unwrap() ; // dont want to create a String
return; // how to keep the black terminal open in Windows ? need pause
}
// . . .
// . . .
}
If you want to keep the terminal from closing you can do something like this:
fn main() {
pause_before_close("Press enter to exit");
}
/// If the Windows terminal would close immediately then insert a pause.
#[cfg(windows)]
fn pause_before_close(message: &str) {
use std::ffi::c_void;
use std::io::{self, stdin, Read};
use std::os::windows::io::AsRawHandle;
const FILE_TYPE_CHAR: u32 = 2;
#[link(name = "kernel32")]
extern "system" {
fn GetFileType(hFile: *mut c_void) -> u32;
fn GetConsoleProcessList(processList: *mut u32, count: u32) -> u32;
}
// Make sure stdin and stdout look like Windows console handles.
let is_console_stdio = unsafe {
GetFileType(io::stdout().as_raw_handle()) == FILE_TYPE_CHAR
&& GetFileType(io::stdin().as_raw_handle()) == FILE_TYPE_CHAR
};
// Test if we're the only process running in the terminal.
let is_standalone = unsafe {
let mut buffer = [0u32; 1];
let count = GetConsoleProcessList(buffer.as_mut_ptr(), 1);
count == 1
};
// If we're using console handles and we're the only process running in the terminal
// then the terminal will exit immediately unless we pause.
if is_console_stdio && is_standalone {
println!("{}", message);
stdin().lock().bytes().next();
}
}
#[cfg(not(windows))]
fn pause_before_close(_message: &str) {}