【问题标题】:How to detect if the user clicked the X button in the leave event of a text box如何检测用户是否在文本框的离开事件中单击了X按钮
【发布时间】:2015-04-23 14:36:25
【问题描述】:

我有一个 TextEditor 的 Leave 事件,在该事件中我执行验证是否需要输入并显示错误消息。 在执行验证之前,我会检查表单是否正在处理,或者是否单击了“取消”按钮。在这种情况下,我退出离开事件。 但是,如果用户单击 X 按钮,这两项检查不会捕捉到这一点,并且会显示错误消息。如果用户单击 X 按钮,我不希望显示错误消息。我怎样才能做到这一点?

private void TitleTextEditor_Leave(object sender, EventArgs e)
{
  UltraTextEditor _currentControl = sender as UltraTextEditor;
  if (this.CancelUButton.Focused || this.Disposing)
  {
    return;
  }
  if (_currentControl.Text.IsNullOrStringEmpty())
  {
    MessageBox.Show("Title is required.");
  }
}

【问题讨论】:

    标签: c# winforms events formclosing


    【解决方案1】:

    如果您想抑制显示的验证错误消息,这是一个棘手的问题。超越它的唯一体面方法是检测 WM_CLOSE 消息 Winforms 代码看到它并在具有焦点的控件上生成 Validating 事件。

    粘贴此代码以解决您的问题:

        protected override void WndProc(ref Message m) {
            // Prevent validation on close:
            if (m.Msg == 0x10) this.AutoValidate = AutoValidate.Disable;
            base.WndProc(ref m);
        }
    

    不要认为你大喊大叫。 ErrorProvider 组件是一种非常体面的方式来显示验证错误并对其进行处理。当表单在关闭时验证自己时,没有什么严重的问题,你只需要这样做:

        private void Form1_FormClosing(object sender, FormClosingEventArgs e) {
            e.Cancel = false;
        }
    

    【讨论】:

    • 感谢您的解决方案。我会使用它并告诉你结果如何。
    • 至于显示错误信息,这是用户的要求,所以我们必须这样做。
    【解决方案2】:

    FormClosingEventArgs 中有一个CloseReason 属性,您可能可以使用它。

    【讨论】:

    • 我需要检查文本编辑器的离开事件。当控件处于 FormClosing 事件中时,为时已晚。但感谢您的意见。
    【解决方案3】:

    如何判断一个控件的表单是否已经关闭。我已经听过 VisibleChanged 事件以预测表单,因为 ParentChanged 可能在控件添加到表单之前发生(例如,如果它在面板中)。您可能还想在第一个事件之后取消订阅 VisibleChanged 事件。

            //put this at class level
            bool _parentClosed;
            //put this in controls constructor
            //when control first becomes visible
            this.VisibleChanged += (s1, a1) =>
            {
                //find parent Form (not the same as Parent)
                Form form = this.FindForm();
    
                //If we are on a Form
                if (form != null)
                    //subscribe to it's closing event
                    form.Closing += (s2, a2) => { _parentClosed = true; };
                else
                    throw new Exception("How did we become visible without being on a Form?");
            };
    

    【讨论】:

    • 我不确定这对我的问题有什么帮助。
    猜你喜欢
    • 2013-03-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-07
    • 2011-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多