Re: destroying a window on windows

eryk sun <[email protected]> Thu, 18 May 2017 02:12:29 +0000
Newsgroups gmane.comp.python.ctypes
Message-ID <CACL+1au_azBz367gEvPhG3Uq3hPXKWoumn4QGjejGUL=H185Ag@mail.gmail.com>
On Wed, May 17, 2017 at 11:10 PM, Michael C
<[email protected]> wrote:
> Apparently even though the MSDN says, given a handle, it would kill the
> window, but it doesn't do that for me. Am I doing it properly?
>
> import time
> import ctypes
> User32 = ctypes.WinDLL('User32', use_last_error=True)
>
> handle = User32.GetForegroundWindow()
> print(handle)
> time.sleep(2)
> User32.DestroyWindow(handle)

You're not checking the BOOL return value to see whether the call
succeeded. If it failed, you need to raise an exception for the
thread's last error value. Do this in a ctypes errcheck function. For
example:

    def _check_bool(result, func, args):
        if not result:
            raise ctypes.WinError(ctypes.get_last_error())
        return args

    User32.DestroyWindow.errcheck = _check_bool

With this check in place, if User32.DestroyWindow(handle) fails,
you'll get an idiomatic exception. Chances are that the foreground
window doesn't belong to your thread, and you haven't read the fine
print in the remarks on MSDN:

   A thread cannot use DestroyWindow to destroy a window created by a
different thread.

Thus it's probably failing with ERROR_ACCESS_DENIED (5). Try sending
the window a WM_CLOSE message instead.

------------------------------------------------------------------------------
Check out the vibrant tech community on one of the world's most
engaging tech sites, Slashdot.org! http://sdm.link/slashdot