3

I am using winit crate in Rust to create a new window. My program initially creates a CLI, and the GUI window is created based on an optional input from the user in CLI. How do I close the newly created window without exiting the process and closing the program completely.

The documentation and examples I have seen all use ControlFlow::Exit to handle the CloseRequested event, but that exits from the entire program; I only want to close the window that was created and continue running the rest of the code in the CLI. If there is an OS-specific command, I am targeting the windows OS.

Ken White
  • 123,280
  • 14
  • 225
  • 444
nuacras
  • 33
  • 3

1 Answers1

1

To close the window, just drop the Window object.

However, I suspect you might be looking to also exit the event loop. That is not possible on all platforms, which is why you don't see documentation covering it often. To run the event loop and have an opportunity to exit it, use winit::platform::run_return::EventLoopExtRunReturn::run_return(), which is a trait implemented only on those platforms which can support returning from the event loop (which include Windows). Within that run_return(), using ControlFlow::Exit from the event handler will return control to the calling function, instead of exiting the process.

You could also do one of these things instead of using run_return():

  • Structure your program so that it continues running, with the CLI interface, within the winit event loop after having closed the window.
  • Run the CLI interactions on a different thread.
Kevin Reid
  • 37,492
  • 13
  • 80
  • 108
  • 1
    I suspect the goal here is to add a command to a CLI interface that opens a GUI window with winit and returns to the CLI when it is closed, without needing to entirely restructure the larger application around winit. In that case, run_return is unlikely to work, as it can only be run once per process. Winit, by design, appears to be largely unsuitable for these situations. – cge Oct 24 '22 at 17:48
  • Using 'run_return()' and restructuring my code so that the CLI interface is enclosed within the event loop worked*. Using 'ControlFlow::Exit' returned the program control to the command line but the window that was created is stuck in the process memory and not destroyed (i was not able to figure out how to drop it from inside the run_return). Setting 'window.set_visible(false)' solved this, though I am not sure how "safe" or good this practice is. @cge - I had to bring my gui code inside the main CLI function (instead of having it in a separate module/function) to get it working – nuacras Oct 24 '22 at 18:48
  • 1
    @nuacras If you can't drop the window because of a "can't move out" sort of problem, then consider putting it in an `Option` — then assigning `None` or using `.take()` will always drop the `Window`. – Kevin Reid Oct 24 '22 at 19:10