- 1 year ago
How to create the main window (UWP/windows-rs)
To create the main window using UWP (Universal Windows Platform) and the windows-rs crate in Rust, you can follow these steps:
Set up a new UWP project: Start by creating a new UWP project in Rust. You can use the
cargo
command-line tool to create a new project with the UWP template. Open a command prompt or terminal and execute the following command:shellcargo new my_uwp_app
This will create a new Rust project with the name "my_uwp_app".
Add windows-rs crate: Open the
Cargo.toml
file of your project and add thewindows
crate as a dependency. YourCargo.toml
should look like this:toml[package]
name = "my_uwp_app"
version = "0.1.0"
edition = "2021"
[dependencies]
windows = "0.25"
Save the file and run
cargo update
to fetch the windows-rs crate.Create the main window: Open the
src/main.rs
file and remove the existing code. Replace it with the following code to create a simple UWP main window:rustuse windows::ui::xaml::controls::{Grid, TextBlock};
use windows::ui::xaml::hosting::WindowsXamlManager;
use windows::ApplicationModel::Activation::LaunchActivatedEventArgs;
use windows::Foundation::TypedEventHandler;
use windows::Win32::WindowsAndMessaging::{CreateWindowExW, DefWindowProcW, DispatchMessageW, GetClientRect, GetMessageW, LoadCursorW, MessageBoxW, MSG, PAINTSTRUCT, PeekMessageW, PostQuitMessage, RegisterClassW, ShowWindow, TranslateMessage, UpdateWindow, WM_CLOSE, WM_CREATE, WM_DESTROY, WM_PAINT, WS_OVERLAPPEDWINDOW, CS_HREDRAW, CS_VREDRAW, CW_USEDEFAULT, IDC_ARROW, MSG};
#[windows::implement(Windows::UI::Xaml::Application)]
struct MyApp;
#[windows::implement(Windows::UI::Xaml::Markup::IComponentConnector)]
struct Connector;
#[windows::implement(Windows::Foundation::IStringable)]
struct Stringable;
impl windows::UI::Xaml::Application {
fn OnLaunched(&self, _: &Option<LaunchActivatedEventArgs>) -> windows::Result<()> {
// Initialize the XAML framework
let _ = WindowsXamlManager::InitializeForCurrentThread()?;
// Create a window
let class_name = "MyApp";
let window_name = "My App";
unsafe {
let hinstance = GetModuleHandleW(None);
let wnd_class = WNDCLASSW {
style: CS_HREDRAW | CS_VREDRAW,
lpfnWndProc: Some(WndProc),
hInstance: hinstance,
lpszClassName: class_name.to_wide(),
..Default::default()
};
RegisterClassW(&wnd_class);
let hwnd = CreateWindowExW(
0,
class_name.to_wide(),
window_name.to_wide(),
WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT,
CW_USEDEFAULT,
CW_USEDEFAULT,
CW_USEDEFAULT,
None,
None,
hinstance,
std::ptr::null_mut(),
);
ShowWindow(hwnd, SW_SHOW);
UpdateWindow(hwnd);
let mut msg = MSG::default();
while GetMessageW(&mut msg, None, 0, 0).into() {
TranslateMessage(&msg);
Dispatch