Creating A MessageBox That Doesn't Stop Code? - c#

Ok, I'm looking for something pretty simple: creating a MessageBox that doesn't stop my code.
I'm guessing I'll have to create a different thread or something? Please advise on the best way to accomplish this.
Thanks!

You could spin up another message pump by calling it on separate thread. MessageBox.Show pumps message so it is safe to do without a call to Application.Run.
public void ShowMessageBox()
{
var thread = new Thread(
() =>
{
MessageBox.Show(...);
});
thread.Start();
}
Edit:
I probably should mention that I do not recommend doing this. It can cause other problems. For example, if you have two threads pumping messages then it is possible for the message box to get stuck behind another form with no way to make it go away if the form is waiting for someone to close the message box. You really should try to figure out another way around the problem.

No, You're going to have to make your own message box form. the MessageBox class only supports behavior similar to .ShowDialog() which is a modal operation.
Just create a new form that takes parameters and use those to build up a styled message box to your liking.
Update 2014-07-31
In the spirit of maintaining clarity for anyone else who finds this through google I'd like to take a second to explain this a bit more:
Under the hood MessageBox is a fancy C# Wrapper around the Windows SDK user32.dll MessageBox Function and thus behaves exactly the same way (after converting .NET Enums into the integers that represent the same thing in the system call.
What this means is that when you call MessageBox.Show() the call is marshaled out to the OS and will block the current thread until an option is selected or the window is killed. To prevent your code from being halted you need to launch the message box on a seperate thread, but this will mean that any result that comes back from the message box (Yes / No / Ok / Cancel / Etc...) will be returned to the separate thread that was tasked to call the message box.
If you act on the result of this message box launched this way you'll have to Dispatch the result back to the UI Thread for Thread Saftey.
Alternatively you can create your own message box form in WinForms / WPF and call it with the .Show() method. Any click events on the buttons will execute on the UI Thread and you will not have to dispatch the calls back to the UI Thread to manipulate things in the UI.

Related

Why does Refresh() not do what DoEvents() does?

I am trying to understand a certain longstanding concept in Windows Forms re: UI programming; following code is from Chris Sells' Windows Forms Programming book (2nd Ed., 2006):
void ShowProgress(string pi, int totalDigits, int digitsSoFar) {
// Display progress in UI
this.resultsTextBox.Text = pi;
this.calcToolStripProgressBar.Maximum = totalDigits;
this.calcToolStripProgressBar.Value = digitsSoFar;
if( digitsSoFar == totalDigits ) {
// Reset UI
this.calcToolStripStatusLabel.Text = "Ready";
this.calcToolStripProgressBar.Visible = false;
}
// Force UI update to reflect calculation progress
this.Refresh();
}
This method is part of small sample application that has another long-running method which calculates Pi. Each time a cluster of digits are calculated, ShowProgress() is called to update the UI. As explained in the book, this code is the "wrong" way of doing things, and causes the UI to freeze when the application is minimized and then brought into the foreground again, causing the system to ask the application to repaint itself.
What I don't understand: Since this.Refresh() is being called repeatedly, why doesn't it process any system repaint event that is waiting for attention?
And a follow-up question: When I add Application.DoEvents() immediately following this.Refresh(), the freeze-up problem disappears. This is without having to resort to Invoke/BeginInvoke, etc. Any comments?
Basically, the reason for this is the way Windows handles messages - it does this in a synchronous way in an internal message loop.
The point is that there was a message that triggered your code. For example a button click. Your application is in the middle of handling the message. From within this handler, you force the refresh which puts another WM_PAINT in the message queue. When your handler finishes, the message loop will surely pick it up and dispatch, thus repainting the control. But your code is not finished, in fact it loops calling your ShowProgress, causing WM_PAINT being queued forever.
On the other hand, the DoEvents() causes an independent instance of the message loop to fire. It's fired from within your code which means that the call stack looks like this:
outer message loop -> your code -> inner message loop.
The inner message loop processes all pending messages, including the WM_PAINT (thus the control is redrawn) but it is dangerous - as it will dispatch all other pending messages, including button clicks, menu clicks or event closing your application with the X at the top-right corner. Unfortunately, there's no easy way to make the loop to process the WM_PAINT only which means that calling DoEvents() exposes your application to subtle potential problems involving unexpected user activity during the execution of your code which triggers the DoEvents.

messagebox without wait or suspend

I need to show a message box to user, with yes no options, but not to suspend the process of my function, it is a lengthy function that takes a minute or so to complete.
the task of messagebox is to asks the user to continue or not. if the user clicks yes, nothing special happens, the work continues to complete, if user don't clicks any buttons, the process must do the task, and when it finishes, the messagebox must disappears, but if the user clicks no, the function must exit.(like the calculator when calculating for example 10000000!).
Sounds like a good time to use a Background Worker. Keeps the UI responsive, while the background task does the long computation. It supports cancellation.
For your problem you can write your own form and handle events Also as Mark suggested you can use the benefit of background. In fact message box doesn't have public constructor to create it and assign some events, So you should write it yourself with your own form.

Form Visiblity Problem

Form1.button_Click(...) {
// Show a dialog form, which runs a method <CheckBalance()> on it's OnLoad Event.
var modemDialog = new ModemDialog("COM25");
modemDialog.ShowDialog();
// the user can't see this dialog form until the method <CheckBalance()> terminates.
}
Is it possible to show first the dialog then run the specified method?
THanks.
That is correct and expected. Winforms UI is inherently single-threaded. Having a function call like "CheckBalance" in the form load event will prevent the form from showing until the form load event completes. Depending on the duration of the task, you have a number of options available to you:
If it's a fast task, compute it ahead of time before showing the form
If it's something the user may want to initiate, move it to a button on the new form, so it's only calculated on the request of the user
If it's a long running task that takes some time, you'll need to move it off in to another thread. Using a BackgroundWorker is recommended.
OnLoad occurs before the form is shown to allow you to initialise the form and variables and what not, which means it is synchronous. The form will not show until you return from that function.
If you want to asynchronously run the CheckBalance() method, then you can use a few techniques, such as utilising the Threading, ThreadPool or Tasks API to shift that work to a background thread, and returning immediately so that the form is shown.
Here is an example of using a Task to perform the same action, but asynchronously so that the form immediately shows:
Action<object> action = () => { CheckBalance(); };
new Task(action).Start();
Please note that if you access the UI thread, you'll need to beware of thread-safety and invocation.
The simple way to make sure your form is visible before CheckBalance is run is to use this code in the form load handler:
this.BeginInvoke((Action)(() => this.CheckBalance()));
This will push the execution of the CheckBalance method onto the UI thread message pump so will execute after all preceding UI code is complete.
Others are correct though that the UI will still be blocked as CheckBalance executes. You probably want to run it on a background thread to prevent this.

C# WinForms child form not getting redrawn after Show()

I am working on a C# WinForms app, and I want it to be able to pop open a non-modal dialog which will get redrawn and be interactive at the same time as the main window/form.
The main window is using a SerialPort and displaying data transfer counts, which are continually increasing via a SerialDataReceivedEventHandler.
I can use ShowDialog() which seems to work in a modal fashion, but the main window data counters freeze while the dialog is in use, and I think eventually the serial buffers are overrun.
I think I want to use Show(), but if I do this the dialog appears on screen half-drawn, then is not drawn or interactive any more (gets trashed if I drag another window across it). It stays onscreen until I close the main app window.
Perhaps I should be starting another thread or, likely, am just doing something wrong. I don't usually do C# or Windows programming (maybe you can tell.)
Edit after comments (thanks, commenters):
I think maybe most things are getting run under whatever thread the serial receive event handler gets called under. When starting up my app I create a class to handle the serial, which includes:
com.DataReceived += new SerialDataReceivedEventHandler(SerialRxHandler);
The only code that I have written to care about threads is some functions to update the counters and log listbox, which I found had to be wrapped with some InvokeRequired to stop me getting complaints about thread switching:
delegate void SetCountDelegate(TextBox tb, int count);
internal void SetCount(TextBox tb, int count) {
// thread switch magic
if (InvokeRequired) {
BeginInvoke(new SetCountDelegate(SetCount), new object[] { tb, count });
} else {
tb.Text = String.Format("{0}", count);
}
}
So maybe I shouldn't be trying to Show() a form on this thread. Another InvokeRequired block, or should I be doing things completely differently?
Suppose I'll answer myself..
Prompted by commenters and a bit of thinking, I did an Invoke() to switch to the UI thread before trying to create and Show() my child dialog. That worked.

WinForm And Looping

I have a WinForm set up and a process that loops until a button is pressed on the form.
When I try to run my code, the form does not even display. I suspect this is because the code gets stuck in the loop and doesn't get far enough to display the WinForm. How can I get the form to display and the loop to run after that point?
If you're looping because you need to do something with the GUI periodically while waiting for input, I suggest using a Timer control and its Tick event.
If you want to do non-GUI things while waiting, a more traditional timer is better suited to the task,
You should probably run the loop in a background thread. The BackgroundWorker class makes this pretty easy to do.
Don't do that.
Windows Forms (like most modern user interface development toolkits) is an event-driven framework. You should never use a loop that "waits" for something to happen; instead you want to use an event that triggers something to happen.
Essentially what's happening is this: WinForms has a loop running a message pump that listens for events from Windows and triggers C# events in response to them. Your code is executing on the same thread as that message pump (it has to, since in WinForms only one thread is allowed to touch any given control). So if you put that thread into a loop, the WinForms code that should be pumping messages isn't, and your user interface appears to hang, since it isn't responding to any messages from Windows. (If you keep clicking it, you will fill up the message queue and get a dialog box that says "This application has stopped responding, do you want to terminate?" or something like that.)
The correct solution is to do one of the following:
Use a Timer
Use a BackgroundWorker
Use a ThreadPool
Another solution that would work, but is not a good idea is:
Use Application.DoEvents() -- but please don't actually do this
Your form loading is freezing because the UI of a windows form runs in a single thread. And the logic that you put on the Load event of this form is running on that thread.
You can run your loop on a separate thread easily by using a BackgroundWorker component on your windows form. On the event DoWork of your background worker, you place the code that has the loop that should run without block your UI. On the Form.Load event, you can start the background worker component by calling the method RunWorkerAsync. On the event handler of your button, you place a code to stop the background worker by calling CancelAsync method.
The article How to: Implement a Form That Uses a Background Operation shows exactly how to accomplish it.
About your comment on not being able to update the Text of a TextBox from a your background worker component. It happens because it is not allowed to modify the state of a windows forms control from a different thread (your background worker code is running on a separated thread) MSDN documentation says:
Access to Windows Forms controls is not inherently thread safe. If you have two or more threads manipulating the state of a control, it is possible to force the control into an inconsistent state. Other thread-related bugs are possible, such as race conditions and deadlocks. It is important to make sure that access to your controls is performed in a thread-safe way.
A sample of how you can update the state of your windows forms controls from your background thread will be similar to the one below (assuming that the new value is already stored on a String variable named text):
// InvokeRequired required compares the thread ID of the
// calling thread to the thread ID of the creating thread.
// If these threads are different, it returns true.
if (this.textBox1.InvokeRequired)
{
SetTextCallback d = new SetTextCallback(SetText);
this.Invoke(d, new object[] { text });
}
else
{
this.textBox1.Text = text;
}
I borrowed this code snipped from How to: Make Thread-Safe Calls to Windows Forms Controls article. It can provide you more information about how to deal with multi-threaded windows forms.
You can use the form load event to trigger the start of the loop.
So it would handle the event Me.Load
However is it necessary for your loop to be happening inside of the UI?
This happens because your loop is keeping the window function from processing messages, such as those that tell it to repaint itself. Place a call to Application.DoEvents() inside of your loop to allow the UI to continue to function.
However, you need to ask yourself why you're looping like this in the first place. If you're, say, copying a bunch of files, this might make sense. For most tasks, though, responding to a timer tick should do the trick and won't block the UI.
You should run your loop in a background thread using the BackgroundWorker component.
Remember that the background thread cannot directly interact with the UI controls.
To report the progress on the UI, you should call the BackgroundWorker's ReportProgress method in the background thread, and handle the ProgressChanged event to update the UI.
You can call the CancelAsync method when the Button is clicked, and loop until the CancellationPending property is true.

Categories

Resources