Reputation: 243
I'm trying to show a message box when pressing a button on a winforms application, but the MessageBox hangs and never returns a value.
private void btnApply_Click(object sender, EventArgs e)
{
bool current = false;
if (cmbEmergencyLandingMode.SelectedIndex > 0)
{
if (m_WantedData != false)
{
DialogResult dr = MessageBox.Show("Are you sure you want to enable Emergency Landing mode?", "Warning!", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
//i never get to this point
current = (dr == DialogResult.Yes);
}
}
if (m_WantedData == current)
{
//do something
}
else if (m_WantedData != null)
{
//do something else
}
}
Edit: Ok so i got it to work by handling the button event on a background worker:
private void btnApply_Click(object sender, EventArgs e)
{
if (!bwApply.IsBusy)
bwApply.RunWorkerAsync(cmbEmergencyLandingMode.SelectedIndex);
}
void bwApply_DoWork(object sender, DoWorkEventArgs e)
{
bool current = false;
int selectedIndex = (int)e.Argument;
if (selectedIndex > 0)
{
if (m_WantedData != false)
{
DialogResult dr = MessageBox.Show(
"Are you sure you want to enable Emergency Landing mode?",
"Warning!", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
current = (dr == DialogResult.Yes);
}
}
if (m_WantedData == current)
{
//do something
}
else if (m_WantedData != null)
{
//do something else
}
}
thanks to everyone who helped!
Upvotes: 2
Views: 2249
Reputation: 1135
Have you tried specifying the message box owner, as below?
DialogResult dr = MessageBox.Show(
this,
"Are you sure you want to enable Emergency Landing mode?",
"Warning!",
MessageBoxButtons.YesNo,
MessageBoxIcon.Warning);
I've seen an application behave like this if a message box is shown while there are concurrent changes to the UI behind the message box. If the above doesn't help, try reducing the stress on UI processing (i.e. WinAPI messaging) by handling the event asynchronously, as below.
public delegate void ApplyDelegate();
private void btnApply_Click(object sender, EventArgs e)
{
btnApply.BeginInvoke(new ApplyDelegate(ApplyAsync));
}
private void ApplyAsync()
{
bool current = false;
if (cmbEmergencyLandingMode.SelectedIndex > 0)
{
if (m_WantedData != false)
{
DialogResult dr = MessageBox.Show(
this,
"Are you sure you want to enable Emergency Landing mode?",
"Warning!",
MessageBoxButtons.YesNo,
MessageBoxIcon.Warning);
//i never get to this point
current = (dr == DialogResult.Yes);
}
}
if (m_WantedData == current)
{
//do something
}
else if (m_WantedData != null)
{
//do something else
}
}
Upvotes: 1
Reputation: 6849
Try to show message without assigning parent form in MessageBox.Show()
method. I don't know why but, i had similar problem when i have loaded modal window.
if (m_WantedData != false)
{
if (MessageBox.Show("Sample Message", "Are you sure you want to enable Emergency Landing mode?", "Warning!", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes)
{
//DO YOUR STUFF HERE IF YES
}
else
{
}
}
Upvotes: 0