How to get window position and size of a different process?

So I was trying to find out how to get a window position and size by pid or window name. I also don't want to use the windows api because I will be serving to windows and linux. I was also thinking of a way where I could use windows api on windows and using a x11 crate for linux but I dont have a windows computer to test on so I was hoping there would be a crate that does both so I know it will work on both.

I’m not aware of a crate for it, but the code (using windows-sys in this case) is not too complicated:

use std::{os::windows::prelude::OsStrExt, iter::once, ptr::null};
use windows_sys::Win32::{UI::WindowsAndMessaging::{FindWindowW, GetWindowRect}, Foundation::{HWND, RECT}};

fn main() {
    let name_or_id = std::env::args_os().nth(1).unwrap();
    let id: HWND = match name_or_id.to_str().and_then(|s| s.parse().ok()) {
        Some(id) => id,
        None => {
            let name: Vec<u16> = name_or_id.as_os_str().encode_wide().chain(once(0)).collect();
            unsafe { FindWindowW(null(), name.as_ptr()) }
        }
    };
    let mut rect = RECT { left: 0, top: 0, right: 0, bottom: 0 };
    if id != 0 && unsafe { GetWindowRect(id, &mut rect) } != 0 {
        println!("{} {} {}", id, rect.right - rect.left, rect.bottom - rect.top);
    }
}

I've done Windows Rust development on an Azure Windows Server, but I know that would be a bit inconvenient. You should be able to cross-compile to x86_64-pc-windows-gnu from Linux to at least see if the code builds:

rustup target add x86_64-pc-windows-gnu
cargo build -v --target x86_64-pc-windows-gnu

That would be really ugly crate because in case of X11 your window and it's position may not even exist on the machine where process is running, they may only exist on a different machine in the some other corner of the world. Worse: one single process may have windows opened on the many different machines simultaneously.

All that complexity is not needed on Windows and don't forget that on Wayland (default on Ubuntu since version 21.04 and Fedora Linux 36) you can not do that at all.

I think I will just use windows-sys crate for windows and x11 and a wayland crate for linux because its the best I can do

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.