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?
if you use DevExpress, then you can do following: Application have property OpenForms which contains all open forms of application. You steel can`t find specific messagebox but you can close all XtraMessageBox. Or if you run MessageBox in some Task/Thread check it before closing.
You might want to consider a LogFile for your messages, along with a richtextbox(or multiline Textbox) embeded in your main form, you could then post your messages in there(1 per line, along with a timestamp). As for your messagebox problem, im not sure there is a (nice) way to programmatically close them.(Aborting the thread won't work).
you can use below class to create a MessageBox easily:
Usage:
Why not make a custom message box? You could have it display for a fixed amount of time or until your app closes it through code.
Create an instance of your custom message box (child of Form class) and save it as a variable (ex.
MyMessageBox
), then show it withMyMessageBox.Show();
.When you want to take it down, callMyMessageBox.Close();
If you have problems closing it if you opened it in another thread, try calling
MyMessageBox.Invoke(new Action(() => {MyMessageBox.Close();}));
That will run the commandMyMessageBox.Close();
on the same threadMyMessageBox
was created in, as to not cause issues.This worked for me
Now you can use
CloseMessageBox()
to close the message box.But have in mind, the captions must be the same in
CloseMessageBox()
andShowMessageBox()
!Maybe through a global variable but that's up to you.
Make an exception for your criteria to know when to start msgbox or no. Example: