How to display a "please wait" message box while the processing goes on in C#?

I have a windows application in which I am using a web reference to show the current SMS balance in the account of a particular user.Here is the code that I am using:

Thread t1 = new Thread(new ThreadStart(ShowWaitMessage)); t1.Start(); XmlNode xmlnde = ws.BSAcBalance(txtLoginId.Text, txtPassword.Text); string sResponse = xmlnde.ChildNodes[0].InnerXml; if (sResponse.Contains("Authentication Failed")) { t1.Abort(); MessageBox.Show("Invalid login id or password !", "Information", MessageBoxButtons.OK, MessageBoxIcon.Asterisk); } else { t1.Abort(); MessageBox.Show("Total balance in your account is Rs : " + sResponse , "Information", MessageBoxButtons.OK, MessageBoxIcon.Asterisk); }
public void ShowWaitMessage() { MessageBox.Show("Please Wait ......"); }

The ws.BSAcBalance is the method that connects the application to the web, it takes some 2 to 3 seconds to execute. In the meanwhile, I want to display a "Please Wait" message for which I am trying to use threading and displaying the message through a message box.Now once the desired operation is completed, I want the "Please Wait" message box to hide, but that doesn't happen.What should I do ?

6

1 Answer

MessageBox is designed to take user's input. So it does NOT present any "native" means to close it programmatically. You have 2 options:

Option 1.

a) Define a new class WaitForm, derived from System.Windows.Forms.Form;

b) Define public method CloseMe in WaitForm that would execute Form.Close() once being called from outside.

c) Create an instance of WaitForm when you need to display the wait message and call its inherited method ShowDialog().

d) Once your operation is completed, call CloseMe from you thread.

Option 2:(force MessageBox closing)

Use Windows API function FindWindow, which is not native for .NET. So you will have to include:

[DllImport("user32.dll", EntryPoint = "FindWindow", SetLastError = true)]
static extern IntPtr FindWindowByCaption(IntPtr ZeroOnly, string lpWindowName);
  • and then, once the operation is done, call

IntPtr hWnd = FindWindowByCaption(IntPtr.Zero, <YourWaitMessageBoxTitle>); if (hWnd.ToInt32() != 0) PostMessage(hWnd, WM_CLOSE, 0, 0);

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

You Might Also Like