消息框挂起

2024-01-09

我试图在按下 winforms 应用程序上的按钮时显示消息框,但 MessageBox 挂起并且从不返回值。

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:好的,我通过处理后台工作人员的按钮事件来使其工作:

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
        }
    }

感谢所有提供帮助的人!


您是否尝试过指定消息框所有者,如下所示?

DialogResult dr = MessageBox.Show(
    this,
    "Are you sure you want to enable Emergency Landing mode?",
    "Warning!",
    MessageBoxButtons.YesNo,
    MessageBoxIcon.Warning);

我曾见过,如果显示消息框,而消息框后面的 UI 发生并发更改,则应用程序会出现这样的行为。如果上述方法没有帮助,请尝试通过异步处理事件来减轻 UI 处理(即 WinAPI 消息传递)的压力,如下所示。

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
    }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

消息框挂起 的相关文章

随机推荐