Ubuntu 17.10下C++定时最小化所有窗口的简易实现方案咨询
Hey there! Since you're new to C++ and don't have much experience with system-specific libraries, let's keep this solution as straightforward as possible. We'll build on your existing code and use a basic Linux tool to handle the window-minimizing part—no fancy GUI libraries required!
Step 1: Install the Required Tool
First, we need wmctrl, a lightweight command-line tool that lets us control windows on Ubuntu's X11 desktop. Open your terminal and run this to install it:
sudo apt update && sudo apt install wmctrl
Step 2: Full Working Code
Here's a complete, heavily commented version of the code that does exactly what you need. It's easy to follow even if you're new to C++:
#include <iostream> #include <chrono> #include <thread> #include <cstdlib> // Needed for the system() function int main() { int minutes; std::cout << "Enter the number of minutes to wait: "; // Make sure we get a valid positive number (no letters/negatives) while (!(std::cin >> minutes) || minutes <= 0) { std::cout << "Oops, please enter a positive whole number: "; // Clear invalid input from the buffer so we can try again std::cin.clear(); std::cin.ignore(1000, '\n'); } // Convert minutes to seconds (since our sleep function uses seconds) int seconds = minutes * 60; std::cout << "Waiting " << minutes << " minutes (" << seconds << " seconds)...\n"; // Pause the program for the specified time std::this_thread::sleep_for(std::chrono::seconds(seconds)); // Run the wmctrl command to minimize all windows (show desktop) std::cout << "Time's up! Minimizing all windows now...\n"; system("wmctrl -k on"); return 0; }
Step 3: What Each Part Does
Let's break it down so you understand every line:
- Input Check: The loop makes sure you can't enter invalid values (like letters or negative numbers) by prompting you again until you get it right.
- Timing: We use
std::this_thread::sleep_forfrom your existing<chrono>and<thread>libraries to pause the program—this is the "timer" part. - Window Minimization: The
system()function runs thewmctrl -k oncommand, which tells Ubuntu to "show the desktop"—this automatically minimizes all open windows in one go.
Step 4: Compile and Run
To get the program working:
- Save the code as
timer.cpp(or any name you prefer). - Open your terminal, navigate to the folder where you saved the file, and run this to compile:
g++ timer.cpp -o timer -std=c++11
(The -std=c++11 flag is required because the <chrono> library needs C++11 or newer.)
- Run the program with:
./timer
Just enter the number of minutes when prompted, and wait—when the timer ends, all your windows will minimize automatically!
内容的提问来源于stack exchange,提问作者Mohammad Jawad Barati

