Last active
April 20, 2023 14:33
-
-
Save Jacobboogiebear/60ab2f14736658bfb22f7324c4bafb79 to your computer and use it in GitHub Desktop.
A small rust file to detect if running in a tty for Tauri (and a macro for println override) ONLY FOR WINDOWS
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Requires crate "windows" using features "Win32_System_Console", "Win32_Foundation", "Win32_UI_WindowsAndMessaging", "Win32_System_Threading", "Win32_System_Diagnostics_ToolHelp" | |
fn get_ppid(pid: u32) -> Option<u32> { | |
use windows::Win32::{ | |
Foundation::{ | |
CloseHandle | |
}, | |
System::{ | |
Diagnostics::ToolHelp::{ | |
CreateToolhelp32Snapshot, | |
TH32CS_SNAPPROCESS, | |
PROCESSENTRY32, | |
Process32First, | |
Process32Next, | |
} | |
} | |
}; | |
unsafe { | |
let mut ppid = 0u32; | |
let snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); | |
let mut pe32 = PROCESSENTRY32::default(); | |
pe32.dwSize = std::mem::size_of::<PROCESSENTRY32>() as u32; | |
if snapshot.is_err() { | |
return None; | |
} | |
let snapshot = snapshot.unwrap(); | |
if !(Process32First(snapshot, &mut pe32).as_bool()) { | |
return None; | |
} | |
while Process32Next(snapshot, &mut pe32).as_bool() { | |
if pe32.th32ProcessID == pid { | |
ppid = pe32.th32ParentProcessID; | |
break; | |
} | |
} | |
CloseHandle(snapshot); | |
return Some(ppid); | |
} | |
} | |
fn is_a_tty() -> bool { | |
use windows::Win32::{ | |
System::{ | |
Threading::GetCurrentProcessId, | |
Console::{AttachConsole, GetConsoleWindow} | |
}, | |
UI::WindowsAndMessaging::GetWindowThreadProcessId | |
}; | |
unsafe { | |
let ppid = get_ppid(GetCurrentProcessId()).unwrap(); | |
AttachConsole(ppid); | |
let console_handle = GetConsoleWindow(); | |
let mut process_id = 0u32; | |
GetWindowThreadProcessId(console_handle, Some(&mut process_id)); | |
return ppid == process_id; | |
} | |
} | |
fn setup_console() { | |
use windows::Win32::System::Console::{FreeConsole, AttachConsole, ATTACH_PARENT_PROCESS}; | |
unsafe { | |
FreeConsole(); | |
AttachConsole(ATTACH_PARENT_PROCESS); | |
} | |
} | |
pub fn initalize(is_gui: fn(), is_console: fn()) { | |
if is_a_tty() { | |
setup_console(); | |
is_console(); | |
} else { | |
is_gui(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment