Skip to content

Instantly share code, notes, and snippets.

@windoze
Last active July 13, 2024 14:02
Show Gist options
  • Save windoze/1f85513e4832cab2f952ab85e641a231 to your computer and use it in GitHub Desktop.
Save windoze/1f85513e4832cab2f952ab85e641a231 to your computer and use it in GitHub Desktop.
Access console when a GUI program starts from console.
/// Attach console from parent process and hold it until being dropped.
/// Used to access console in Windows GUI application when it's started from console.
/// Does nothing if it's started from GUI because `AttachConsole` will fail.
/// ```no_run
/// // Add this line at the beginning to suppress console window
/// #![windows_subsystem = "windows"]
/// // ...
/// fn main() {
/// // Attach console from parent process, if any
/// let c = ConsoleHolder::new();
/// // App code here
/// // ...
/// c.wrap(()) // Keep console open until the end of the program
/// }
/// ```
struct ConsoleHolder;
impl ConsoleHolder {
/// Attach console from parent process.
pub fn new() -> Self {
#[cfg(windows)]
unsafe {
winapi::um::wincon::AttachConsole(0xFFFFFFFF);
}
Self
}
pub fn wrap<T>(self, t: T) -> T {
t
}
}
#[cfg(windows)]
impl Drop for ConsoleHolder {
fn drop(&mut self) {
unsafe {
winapi::um::wincon::FreeConsole();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment