问题
I am writing c++ library in Linux using gcc. Program opens web pages in new browser windows with
system("firefox https://www.webpage.com");
After that I use xlib to determine identifiers of each opened browser window. Then program raises firefox windows one by one using
XRaiseWindow(display, window)
in order to make a screenshot of each window and OCR.
But if I close browser window manually and try to use
XRaiseWindow
with the corresponding identifier it generates BadWindow error and terminates the program.
So how can I check in xlib if window with given window
identifier exists?
回答1:
From the X FAQ:
169) How do I check whether a window ID is valid?
My program has the ID of a window on a remote display. I want to check whether the window exists before doing anything with it.Because X is asynchronous, there isn't a guarantee that the window would still exist between the time that you got the ID and the time you sent an event to the window or otherwise manipulated it. What you should do is send the event without checking, but install an error handler to catch any
BadWindow
errors, which would indicate that the window no longer exists. This scheme will work except on the [rare] occasion that the original window has been destroyed and its ID reallocated to another window.You can use this scheme to make a function which checks the validity of a window; you can make this operation almost synchronous by calling
XSync()
after the request, although there is still no guarantee that the window will exist after the result (unless the sterver is grabbed). On the whole, catching the error rather than pre-checking is preferable.
Long story short: You can't :P You can only damage control.
来源:https://stackoverflow.com/questions/44025639/how-can-i-check-in-xlib-if-window-exists