Teardown a MessageBox programmatically without user input

Michael Mankus picture Michael Mankus · Oct 28, 2013 · Viewed 11.6k times · Source

I'm using a MessageBox from time to time to pop up alert messages for the user. My particular application can be setup to run remotely so there are times where the user is in front of the computer and other times where the user may not be in front of the computer for hours or even days. Sometimes I popup an alert message using MessageBox but after some period of the time the alert is no longer relevant. For example, I popup an alert that a task can't be completed because of some criteria not being met. A few minutes later that criteria is met and the task begins. That MessageBox is no longer relevant.

I want to be able to programmatically close the MessageBox in these cases where the message is no longer relevant. Is this possible? Currently I create my MessageBox objects in a thread using:

new Thread(() => MessageBox.Show("Some text", "Some caption")).Start();

I do this so that the application can continue to work in the background without being halted by the MessageBox. Any suggestions?

Answer

Andy picture Andy · Oct 28, 2013

This worked for me

public partial class Form1 : Form
{
    [DllImport("user32.dll", EntryPoint = "FindWindow", SetLastError = true)]
    static extern IntPtr FindWindowByCaption(IntPtr ZeroOnly, string lpWindowName);

    [DllImport("user32.Dll")]
    static extern int PostMessage(IntPtr hWnd, UInt32 msg, int wParam, int lParam);

    const UInt32 WM_CLOSE = 0x0010;

    Thread thread;

    public Form1()
    {
        InitializeComponent();

        thread = new Thread(ShowMessageBox);
        thread.Start();
    }

    void CloseMessageBox()
    {
        IntPtr hWnd = FindWindowByCaption(IntPtr.Zero, "Caption");
        if (hWnd != IntPtr.Zero)
            PostMessage(hWnd, WM_CLOSE, 0, 0);

        if (thread.IsAlive)
            thread.Abort();
    }

    static void ShowMessageBox()
    {
        MessageBox.Show("Message", "Caption");
    }
}

Now you can use CloseMessageBox() to close the message box.

But have in mind, the captions must be the same in CloseMessageBox() and ShowMessageBox()!

Maybe through a global variable but that's up to you.