rustwinit

How to to close a window inititated with winit, without exiting program/process?


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.


Solution

  • 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():