- 1 year ago
How to get args from WinMain or wWinMain in Rust?
In Rust, you can retrieve the command-line arguments from the WinMain
or wWinMain
function using the std::env::args
function. Here's an example of how you can do it:
rust#![windows_subsystem = "windows"]
use std::env;
use std::ffi::OsString;
use std::os::windows::ffi::OsStringExt;
use std::ptr;
use std::mem;
use winapi::um::winuser::{MessageBoxW, MB_OK};
fn main() {
// Get the command-line arguments as a collection of OsStrings
let args: Vec<OsString> = env::args_os().collect();
// Convert the command-line arguments to a Vec<String>
let args: Vec<String> = args
.into_iter()
.map(|arg| arg.to_string_lossy().into_owned())
.collect();
// Display the command-line arguments in a message box
let message = args.join("\n");
let message = message.encode_utf16().collect::<Vec<u16>>();
let title = "Command Line Arguments".encode_utf16().chain(Some(0)).collect::<Vec<u16>>();
unsafe {
MessageBoxW(ptr::null_mut(), message.as_ptr(), title.as_ptr(), MB_OK);
}
}
In this example, the std::env::args_os
function retrieves the command-line arguments as a collection of OsString
objects. We then convert each OsString
to a String
using the to_string_lossy
method. Finally, we join the String
arguments into a single message and display it in a message box using the MessageBoxW
function from the winapi
crate.
Note that this example assumes you have the necessary dependencies specified in your Cargo.toml
file, including the winapi
crate for accessing the Windows API.
Make sure to add the following line to your Cargo.toml
file to compile the application as a Windows subsystem application:
toml[profile.release]
# ...
[dependencies]
winapi = "0.3"
Remember to adjust the code according to your specific needs, such as handling errors or using a different UI library for displaying the message.