强制程序关闭MessageBox

26

让我先来介绍一下背景。

我们有一个中等规模的应用程序,它在各个地方(数百处)使用 MessageBox.Show(...)。

这些消息框是工作流程的一部分,用于通知、警告或从用户那里获取输入。如果没有活动,应用程序应自动注销。我们有一个要求,在注销应用程序时,只需清除会话数据、清除视图并隐藏它本身,以便在下次启动时,不必执行启动过程,该过程在时间成本方面很高。

一切运行良好,但是当屏幕上有某个消息框而用户没有响应该消息框,并且由于没有活动而导致应用程序注销时,问题就出现了。问题是消息框不会消失。

如何在隐藏应用程序的同时关闭打开的消息框(如果有的话)?


也许发送键盘的回车或ESC键? :) - Renatas M.
我认为 MessageBox.Show(...) 是模态的,那么程序怎么能发送一个键呢?你是使用线程/任务吗? - Fischermaen
谢谢回复。只是想澄清,使用自定义消息框不是一个选项,因为重新设计的工作量很大。发送 ESC 键也不正确,因为只有活动应用程序才会接收到命令。我正在使用 FindWindow 方法,在通过 id 和消息框标题传递参数后,获取 Msgbox 句柄。获取句柄后,我使用以下 win32 API 关闭它,例如 SendMessage(new HandleRef(null, msgbxcHandler), WM_CLOSE, IntPtr.Zero, IntPtr.Zero); SendMessage(new HandleRef(null, msgbxcHandler), WM_NCDESTROY, IntPtr.Zero, IntPtr.Zero); 到目前为止一切正常。 - NYK
12个回答

0
我找到了一个简单的解决方案,不需要实现任何额外的类或方法。
// create an invisible Form to be the Owner of the MessageBox
Form myMessageBox = new Form() {
   Owner = MainWindow, // in case you have a main application window
   Size = new System.Drawing.Size(0, 0)
};

MainWindow.BeginInvoke(
    new Action(() =>
    {
        MessageBox.Show(
            myMessageBox, //this is key, here you pass the myMessageBox as owner of the Messagebox
            "The Message",
            "The Window Title",
            MessageBoxButtons.OK,
            MessageBoxIcon.Information,
            MessageBoxDefaultButton.Button1
        );
    }
));


if(messageBoxShallBeClosed)
{
    // whenever or whereever you want to close the MessageBox execute the following
    MainWindow.Invoke(
        new Action(() =>
        {
            myMessageBox.Close(); // this closes the MessageBox, since it is the owner of it
        }
    ));
}


0

创建自己的控件并实现您想要的行为。作为一种选择,可以设置一个计时器来关闭此消息框。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接