Ask Your Question

Revision history [back]

How to detect closing of namedWindow by mouse or ALT+F4

I have this simple code for showing an image from the command line:

int main(int argc, char* argv[]) {
    int retStatus = -1;

    if(argc < 2) {
        std::cout << "Please provide a path to on image!" << std::endl;
    } else {
        std::string path = argv[1];
        std::ifstream file(path);
        if(!file) {
            std::cout << "It seems that the file " << path <<
                                           " Does not exist!" << std::endl;
        } else { //file exist :)
            cv::namedWindow(path); //autosize is default so no need to provide it
            cv::Mat src = cv::imread(path); //read the file
            if(!src.data) { //check for validity of the file
                std::cout << "File is corrupted!" << std::endl;
            } else {
                cv::imshow(path, src);
                while(cv::waitKey(1) != 27); //if ESC is not pressed
                src.release();
                retStatus = 0;
            }
        }
    }
    return retStatus;
}

It works, but only if I press the ESC key it terminates the program. If I hit the X on the window by mouse or press ALT+F4 the program does not terminate (but the window will be closed!). So how to detect this closing behavior?