通过避免文本框验证来关闭 C# windows 窗体 [英] Closing the C# windows form by avoiding textbox validation

查看:24
本文介绍了通过避免文本框验证来关闭 C# windows 窗体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个 winform C# 问题.我有一个带有验证事件侦听器的文本框,用于根据正则表达式验证文本框的内容.

This is a winform C# question. I have a textbox with a validating event listener to validate the content of the textbox against a regular expression.

验证后,如果输入的值不正确,我将显示消息框并取消事件,以便鼠标光标移回具有不正确值的文本框.

After the validation, if entered value is not proper,i am showing the messagebox and i am cancelling the event so that mouse cursor move back to the textbox which has improper value.

当我从该文本框移到其他按钮/文本框时,这工作正常.

This is working fine when i move out from that textbox to other buttons/textboxes.

但是当我输入不正确的值并关闭表单(使用右上角的关闭按钮)时,它会验证文本框内容并抛出消息框,并且在我取消事件时表单不会关闭.

But when i enter improper value and close the form (with the close button on right top corner), it validates the textbox contents and throws up the messagebox and form doesnot close as i am cacelling the event.

问题是,当我单击表单右上角的 X 按钮时,我不希望触发验证,因为我正在关闭表单.我该怎么做?

The problem is, when I click the X button on the right top corner of the form, I don't want the validation to be fired because I am closing the form anyway. How can I do this?

我会尽快发布代码片段.

I will post the code snippet as soon as possible.

推荐答案

要使用验证处理程序,例如下面的 'txtIPAddress_Validating()' 处理程序,同时能够关闭表单而无需输入有效条目,我这样做以下:

To use validating handlers such as the 'txtIPAddress_Validating()' handler below while being able to close the form without having to enter valid entries to do so, I do the following:

1) 启动验证处理程序:从要激活验证的控件的控件属性中,双击此控件事件列表中的验证"事件.通过单击此控件的属性表的事件(闪电般的)工具栏按钮可以访问控件事件列表.然后,您可以在自动生成的处理程序中输入代码,其名称结合了控件名称和_Validating".该处理程序中将某些内容确定为无效的部分可以通过添加e.Cancel = true"指令来强制输入有效条目.

1) Initate validating handlers: From the control properties of the control you wish to activate validation for, double click the 'Validating' event from this control event list. A control event list is accessed by clicking this control's property sheet’s event (lightning looking) toolbar button. You can then enter the code in the automatically generated handler with a name combining both the name of the control and '_Validating'. The part of this handler where something is established as invalid can force valid entries by adding the 'e.Cancel = true' instruction.

对于此类验证方法示例,请参阅下面的txtIPAddress_Validating()"和txtMaskBits_Validating()"代码.不要被这些特定示例的完整验证机制分心.为了强制验证,您需要在自己的代码中查看和重现,只需在您自己的验证方法的正确位置添加e.Cancel = true"指令.即该值被识​​别为无效.

For such validating method examples, See 'txtIPAddress_Validating()' and 'txtMaskBits_Validating()' code below. Do not get distracted by the complete validation mechanism of these specific examples. All you need to see and reproduce in your own code in order to force validation is to add the 'e.Cancel = true' instruction at the right place of your own validating method. That is when the value is identified to be invalid.

此时验证应该可以正常工作,但任何关闭表单的尝试都将触发验证,验证将停止并在能够关闭表单之前坚持输入有效值.这并不总是你想要的.如果不是这样,我将继续以下操作.

At this point the validation should work fine but any attempt to close the form will trigger validation which will stop and insist for valid values before being able to close the form. This is not always what you want. When it is not so, I continue with the following.

2) '取消' 按钮也取消(禁用)所有验证:

2) 'Cancel' button that also cancels (disables) all validations:

a) 在表单上放置一个常规的取消"按钮,该按钮与下面的btnCancel_Click()"方法相关联.

a) Place a regular 'Cancel' button on the form which is associated to a method such as the 'btnCancel_Click()' method below.

b) 在常规 'this.close();' 之前指令,添加'AutoValidate = AutoValidate.Disable;'操作说明.该指令禁用所有验证"触发器.请注意,在进行任何验证之前会触发btnCancel_Click"事件.对于将在验证事件后执行的表单关闭事件并非如此.这就是为什么不能从这些表单关闭事件中禁用该验证的原因.

b) Before the regular 'this.close();' instruction, add the 'AutoValidate = AutoValidate.Disable;' instruction. This instruction disables all 'validating' triggers. Note that the 'btnCancel_Click' event is triggered before any validation is taking place. That is not so for the Form Closing events that will all execute after validating events. That is why that validation cannot be disabled from any of these Form Closing events.

c) 要使取消"按钮正常工作,您还需要将此取消"按钮的CausesValidation"属性设置为假".这是必要的,否则单击此按钮将触发验证,然后可以通过上面的AutoValidate = AutoValidate.Disable;"禁用验证说明.

c) For this 'Cancel' button to work correctly, you also need to set the 'CausesValidation' property of this 'Cancel' button to 'false'. This is necessary, otherwise clicking on this button will trigger the validation before validating can be disabled by the above 'AutoValidate = AutoValidate.Disable;' instruction.

此时,您应该可以通过单击取消"按钮退出,而无需先输入有效值.但是,单击表单窗口右上角的X"按钮仍然会强制验证.

At this point, you should be able to quit by clicking on the 'Cancel' button without having to first enter valid values. However, clicking the upper right "X" button of the form's window will still force validation.

3) 使右上角的X"按钮也取消验证:

3) Make the upper right "X" button also cancel validation:

这里的挑战是在执行验证之前捕获此类X"单击事件.任何通过表单关闭处理程序执行此操作的尝试都将不起作用,因为一旦执行到达此类处理程序就为时已晚.但是,可以通过覆盖 WndProc() 方法并测试m.Msg == 0x10"条件来迅速捕获X"按钮的单击.当该条件为真时,前面介绍的AutoValidate = AutoValidate.Disable;"在这种情况下,指令也可以再次用于禁用整体验证.有关此类方法的代码示例,请参见下面的 WndProc() 方法.您应该能够在表单的类中复制和粘贴该方法.

The challenge here is to trap such "X" clicked event before validation is executed. Any attempt to do so through a Form Closing handler will not work because it is then too late once execution reaches such handler. However, the click of the "X" button can be captured promptly via overriding the WndProc() method and testing for a 'm.Msg == 0x10' condition. When that condition is true, the previously introduced 'AutoValidate = AutoValidate.Disable;' instruction can again be used to disable overall validation in that case as well. See the WndProc() method below for a code sample of such method. You should be able to copy and paste that method as is in your form's class.

此时,取消"和X"按钮都应该取消验证.但是,可用于关闭表单的转义键却没有.当使用表单的CancelButton"属性将此转义键链接到表单的取消"按钮时,会激活此类转义键.

At this point, both the 'Cancel' an "X" buttons should cancel valdations. However, the escape key that can be used to close a form does not. Such escape key is activated when the form's 'CancelButton' property is used to link this escape key to the form's 'Cancel' button.

4) 使转义键也取消验证:

4) Make the escape key also cancel validation:

类似于X"按钮,可以通过覆盖现有方法来捕获转义键.那就是 ProcessDialogKey() 方法.再一次,之前介绍的'AutoValidate = AutoValidate.Disable;'指令也可用于禁用转义键的整体验证.请参阅下面代码中的ProcessDialogKey()"覆盖方法,了解如何完成此操作.同样,您应该能够在您自己的表单类中复制和粘贴该方法.

Similar to the "X" button, the escape key can be captured by overriding an existingmethod. That is the ProcessDialogKey() method. One more time, the previously introduced 'AutoValidate = AutoValidate.Disable;' instruction can be used to disable overall validation for the escape key as well. See the ‘ProcessDialogKey()’ overridden method in the code below to see how this can be done. Here again, you should be able to copy and paste that method as is in your own form's class.

此时你应该完成了!

进一步考虑:

值得注意的是,以下两种其他关闭窗口的方法此时也应该可以正常工作.这两种方式分别是:

It is good to notice that the following two other ways to close the window should also work fine at this point. These two ways are:

  • 左上方窗口图标按钮的关闭"选项.
  • 按 Alt+F4 触发与上述关闭"选项相同的关闭操作.

一旦您引入了上面第 3 点中描述的X"按钮捕获机制,这两种关闭窗口的方式也开始取消验证.

These two ways of closing the window started to also cancel validation once you introduced the "X" button capture mechanism described in point 3 above.

到目前为止,这对我来说就是这样.希望这会有所帮助!

That is it for me for this so far. Hoping this helps!

我的代码示例如下:

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

    // To capture the Upper right "X" click
    protected override void WndProc(ref Message m)
    {
        if (m.Msg == 0x10) // The upper right "X" was clicked
        {
            AutoValidate = AutoValidate.Disable; //Deactivate all validations
        }
        base.WndProc(ref m);
    }

    // To capture the "Esc" key
    protected override bool ProcessDialogKey(Keys keyData)
    {
        if (keyData == Keys.Escape)
        {
            AutoValidate = AutoValidate.Disable;
            btnCancel.PerformClick(); 
            return true;
        }
        return base.ProcessDialogKey(keyData);
    }
    public bool IsValidIP(string ipaddr)
    {
        string pattern = @"^([1-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])"+
        @"(.([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3}$";

        Regex check = new Regex(pattern);
        bool valid = false;

        if (ipaddr == "")
        {
            valid = false;
        }
        else
        {
            valid = check.IsMatch(ipaddr, 0);
        }

        return valid;
    }

    private void txtIPAddress_Validating(object sender, CancelEventArgs e)
    {
        string address = txtIPAddress.Text;
        if (!IsValidIP(address))
        {
            MessageBox.Show("Invalid IP address!");
            e.Cancel = true;
        }
    }

    private void cmbMaskBits_Validating(object sender, CancelEventArgs e)
    {
        int MaskBitsValue = Convert.ToInt32(cmbMaskBits.Text);

        if (MaskBitsValue<1 || MaskBitsValue>30)
        {
        MessageBox.Show("Please select a 'Mask Bits' value between 1 and 30!");
        e.Cancel = true;
        }
    }

    private void btnCancel_Click(object sender, EventArgs e)
    {
        // Stop the validation of any controls so the form can close.
        // Note: The CausesValidation property of this <Cancel> button
        //       must also be set to false.

        AutoValidate = AutoValidate.Disable;
        this.Close();
    }

这篇关于通过避免文本框验证来关闭 C# windows 窗体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆