Search code examples
pythonwindowspython-3.xctypesmessagebox

Python How to keep MessageboxW on top of all other windows?


Context:

I have a small script that alerts the user of an event by creating a message box using the Windows in built message box (Ref: MSDN MessageBox) which is imported using ctypes. This script is for Windows OS.

Problem:

Currently, the message box will appear on top of all other windows, but because it's such a small window, a user can easily click onto another window which could hide the message box.

What I want

I want to keep the message box always on top of other windows. If this can't be done, then alternatively is there a way to increase the dimensions of the message box?

Example Code:

import ctypes

ctypes.windll.user32.MessageBoxW(0, text, title, 0x00010000)

Solution

  • import ctypes
    
    text = 'Using MB_SYSTEMMODAL'
    title = 'Some Title'
    
    ctypes.windll.user32.MessageBoxW(0, text, title, 0x1000)
    

    MB_SYSTEMMODAL (0x1000) has the WS_EX_TOPMOST (0x40000) style.

    The MessageBoxEx function seems to work good with using just the WS_EX_TOPMOST (0x40000) style.

    import ctypes
    
    text = 'Using WS_EX_TOPMOST'
    title = 'Some Title'
    
    ctypes.windll.user32.MessageBoxExW(0, text, title, 0x40000)
    

    The MessageBox function has no parameters to change size. Perhaps an alternative like tkinter or another gui toolkit might be able to change messagebox size (though it maybe not if it just a wrapper for MessageBoxW) or you could perhaps create a custom window to use.

    See MSDN MessageBox function for values to use.

    See also MSDN MessageBoxEx function.