Search code examples
windowswinapiuser-interfacemessagebox

Detecting creation of a MessageBox


My application is loading 3rd party DLLs, and some of this DLLs open MessageBox windows.

Is there a way for me to detect when such a window was being opened?


Solution

  • You'll need a CBT hook to receive a notification when a MessageBox window is displayed. You install this by calling the SetWindowsHookEx() function and specifying WH_CBT for the hook ID parameter. The hook callback function will provide you a handle to the MessageBox window, which you can then use to close it.

    If you know exactly when to expect the MessageBox is being created and shown, then you can adopt a lighter and simpler approach than a global hook. This would involve calling the FindWindowEx function to get a handle to the MessageBox window, which you can likewise use to close it.

    Of course, to close it properly, you will need to know which type of MessageBox it is (that is, which of the standard button choices that it displays) so that you can simulate a click of the desired button. Simply managing to get the MessageBox to disappear off of the screen without providing a valid answer is highly likely to have unexpected results in terms of the library code.

    It bears explicit mention that this is really bad behavior on the part of a DLL. Unless absolutely necessary, ditch whatever 3rd party that is foisting such poorly written code upon you. If it is absolutely necessary, well then that's a red flag: work hard to eliminate it as a necessity. You shouldn't have to write and maintain gobs of code to work around their inability to get the big obvious things right.