Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

assign a window to a specific monitor/display [feat] #6394

Closed
don41382 opened this issue Mar 3, 2023 · 12 comments
Closed

assign a window to a specific monitor/display [feat] #6394

don41382 opened this issue Mar 3, 2023 · 12 comments

Comments

@don41382
Copy link

don41382 commented Mar 3, 2023

Describe the problem

I can't programmatically assign / move a window two a display in a multi monitor setup.

Describe the solution you'd like

It would be nice, if the WindowBuilder would support assigning a Monitor/Display to a new window.

Alternatives considered

No response

Additional context

No response

@don41382 don41382 changed the title move Window to a specific display [feat] assign a window to a specific monitor/display [feat] Mar 3, 2023
@metkm
Copy link

metkm commented Mar 5, 2023

should you be able to move your window between monitors or what you think is just opening the window on the other monitor?

@don41382
Copy link
Author

don41382 commented Mar 6, 2023 via email

@metkm
Copy link

metkm commented Mar 6, 2023

Maybe you can do something like this for now. The one weird this was that my x and y positions of display 2 were mixed with display 1. This could be a problem with my system. I don't know.

use tauri::{Position, Window, WindowBuilder};

fn move_window_to_other_monitor(window: &Window, i: usize) -> tauri::Result<()> {
    let monitors = window.available_monitors()?;
    let monitor = monitors.get(i).ok_or(tauri::Error::CreateWindow)?;

    let pos = monitor.position();

    window.set_position(Position::Physical(
        tauri::PhysicalPosition{
            x: pos.x,
            y: 0
        })
    )?;

    window.center()?;
    Ok(())
}

fn main() {
    tauri::Builder::default()
        .setup(|app| {
            let window =
                WindowBuilder::new(app, "Main", tauri::WindowUrl::App("index.html".into()))
                    .build()?;

            move_window_to_other_monitor(&window, 1);

            Ok(())
        })
        .run(tauri::generate_context!())
        .expect("error while running tauri application");
}

@amrbashir
Copy link
Member

  • specify the monitor on window creation

you can use WindowBuilder::position to determine the position of a window which can be on another monitor. However, this in itself is not much useful without getting the monitors info before creating the window so I will open a PR to add AppHandle::available_monitors() and AppHandle::primary_monitor().

move a window after creation via a move_to_monitor method

Not needed and not very much practical since we can't know which coordinates inside that monitor would you want to assign your window so the solution given by @metkm is the way to do it.

@don41382
Copy link
Author

don41382 commented Mar 6, 2023

Thanks for you support @amrbashir and @metkm. This helps me already!

@don41382 don41382 closed this as completed Mar 6, 2023
lucasfernog added a commit that referenced this issue Jul 12, 2023
…6403)

Co-authored-by: Lucas Nogueira <lucas@tauri.studio>
@somyaranjan007
Copy link

How to stop tauri app at mutliple monitors and run only on user choose monitor

@dolev146
Copy link

so this is closed because the solution is what?

@dolev146
Copy link

@FabianLars also this is not clear :( makes me sad

@dolev146
Copy link

Maybe you can do something like this for now. The one weird this was that my x and y positions of display 2 were mixed with display 1. This could be a problem with my system. I don't know.

use tauri::{Position, Window, WindowBuilder};

fn move_window_to_other_monitor(window: &Window, i: usize) -> tauri::Result<()> {
    let monitors = window.available_monitors()?;
    let monitor = monitors.get(i).ok_or(tauri::Error::CreateWindow)?;

    let pos = monitor.position();

    window.set_position(Position::Physical(
        tauri::PhysicalPosition{
            x: pos.x,
            y: 0
        })
    )?;

    window.center()?;
    Ok(())
}

fn main() {
    tauri::Builder::default()
        .setup(|app| {
            let window =
                WindowBuilder::new(app, "Main", tauri::WindowUrl::App("index.html".into()))
                    .build()?;

            move_window_to_other_monitor(&window, 1);

            Ok(())
        })
        .run(tauri::generate_context!())
        .expect("error while running tauri application");
}

so how to use this ?

// Prevents additional console window on Windows in release, DO NOT REMOVE!!
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
use tauri::{Position, Window, WindowBuilder};
fn move_window_to_other_monitor(window: &Window, i: usize) -> tauri::Result<()> {
  let monitors = window.available_monitors()?;
  let monitor = monitors.get(i).ok_or(tauri::Error::CreateWindow)?;

  let pos = monitor.position();

  window.set_position(Position::Physical(
      tauri::PhysicalPosition{
          x: pos.x,
          y: 0
      })
  )?;

  window.center()?;
  Ok(())
}

fn main() {
  tauri::Builder::default()
    .run(tauri::generate_context!())
    .expect("error while running tauri application");
}

@dolev146
Copy link

I am trying to use the function without luck all the type types errors

@FabianLars
Copy link
Member

If you're not familiar with Rust (and don't want to be) then the monitor apis are also available in javascript (if it's about your primary window then you'll have to spawn it hidden and only show() it once you moved it to the correct monitor).

@dolev146
Copy link

I solved it with this

// Prevents additional console window on Windows in release, DO NOT REMOVE!!
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]

use tauri::{Manager, PhysicalPosition, PhysicalSize};

fn main() {
  tauri::Builder::default()
  .setup(|app| {
    let win = app.get_window("main").unwrap();

  // Get available monitors
  let available_monitors = win.available_monitors().expect("Failed to get monitors");

      // Check if monitor 2 exists (index 1)
      if available_monitors.len() > 1 {
        // destinationMonitorId = 0 and max_x = available_monitors[destinationMonitorId].x
        // loop over monitors from 1 to len of monitors 
        // compare the x of each monitor with the maxX and 
        // if the new X is bigger than the current maxX then replace it and modify the destination monitor id
        let mut destination_monitor_id = 0;
        let mut max_x = available_monitors[destination_monitor_id].position().x;
        for (index, monitor) in available_monitors.iter().enumerate() {
          if monitor.position().x > max_x {
              max_x = monitor.position().x;
              destination_monitor_id = index;
          }
      }


        let monitor = &available_monitors[destination_monitor_id];
        let monitor_position = monitor.position();
        let monitor_size = monitor.size();

        // Move window to the selected monitor
        win.set_position(PhysicalPosition::new(monitor_position.x, monitor_position.y)).expect("Failed to move window");

        // Optionally resize the window to fit the new monitor
        win.set_size(PhysicalSize::new(monitor_size.width, monitor_size.height)).expect("Failed to resize window");
        win.maximize().expect("Failed to maximize window");
      } else {
        eprintln!("Monitor 2 not found!");
      }

      // Show the window after positioning
      win.show().expect("Failed to show window");

    Ok(())
})
    .run(tauri::generate_context!())
    .expect("error while running tauri application");
}

and this

    "windows": [
      {
        "fullscreen": false,
        "closable": true,
        "title": "HaGuide",
        "visible": false,
        "url": "index.html",
        "fileDropEnabled": false,
        "maximized": true,
        "alwaysOnTop": true,
        "focus": true
      }
    ]
  }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

6 participants