c# - 当用户试图关闭使用 Form.ShowDialog() 创建的模态对话框时是否会引发事件?

标签 c# winforms events modal-dialog

长话短说

.ShowDialog() 模态对话框打开并且用户单击原始表单时,对话框的标题栏会闪烁。该事件是否可通过 Windows.Forms API 或任何其他方式访问?


详细信息

这是一个标准的 C# 6 Windows 窗体项目,带有一个父窗体和一个对话框窗口。父表单有一个打开对话框的按钮:

using System;
using System.Windows.Forms;

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        using (var dialog = new Dialog())
        {
            Console.WriteLine("Dialog starting.");

            dialog.ShowDialog(this);

            Console.WriteLine("Dialog done.");
        }
    }
}

.ShowDialog(this) 创建的 Dialog 同样简单,只有一个 OK 按钮和一个 Cancel 按钮:

using System;
using System.Windows.Forms;

public partial class Dialog : Form
{
    public Dialog()
    {
        InitializeComponent();
    }

    private void btnOK_Click(object sender, EventArgs e)
    {
        Close();
    }

    private void btnCancel_Click(object sender, EventArgs e)
    {
        Close();
    }
}

应用程序启动,

enter image description here

当用户点击“Show Modal Dialog”按钮时,button1 事件 Click 被触发,对话框被触发,如第一个片段所示。

enter image description here

当用户在对话框仍处于打开状态时单击原始表单时,对话框的标题栏会闪烁。

enter image description here

是否可以通过 Windows.Forms API 或任何其他方式访问该事件?

在更复杂的应用程序中,如果对话框的输入字段通过验证,我想在用户单击主窗体时关闭模态对话框,如果没有通过,则突出显示无效字段。

我目前正在使用 .Show() 方法显示 dialog,并在 deactivate< 上关闭 dialog/ 事件。但这有两个缺点

  • 当用户点击桌面或其他应用程序时,对话框关闭。
  • 当用户点击对话框时,有时主窗体会隐藏在其他应用程序的窗口后面。

我找到了一个 related WPF question ,答案是非常具体的“”。

最佳答案

正如 Orion_Eagle 所建议的那样,覆盖 WndProc 是可行的方法。 查看this list of windows messages

protected override void WndProc(ref Message m)
{
    //134 = WM_NCACTIVATE
    if (m.Msg == 134)
    {       
        //Check if other app is activating - if so, we do not close         
        if (m.LParam == IntPtr.Zero)
        {                    
             if (m.WParam != IntPtr.Zero)
             {                     
                 //Other form in our app has focus
             }

        }
     }                     

     base.WndProc(ref m);
}

关于c# - 当用户试图关闭使用 Form.ShowDialog() 创建的模态对话框时是否会引发事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33533908/

相关文章:

Javascript - 对象不支持 document.createEvent

javascript - 禁用 Javascript 中的 dom 更改事件?

c# - ppt保存幻灯片时保留源模板

c# - Winforms 文本框每页行数

.net - Silverlight 对比WPF 对比Winforms 有什么特别适合我的目的?

c# - 在数据库中发送带有附件路径的批量电子邮件

events - Vue.js 事件使用全局事件总线从子组件发射到(大)父组件

c# - 如何运行 x64 Debug模式 DLL 是 "Any CPU"?

c# - 使用 C# 编辑 tif 文件

c# - 转换类型时遇到问题