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

查看:169
本文介绍了避免文本框验证关闭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.

验证后,如果输入的值是不妥当的,我显示在MessageBox而我取消该事件,使鼠标光标移动回有不当值的文本框。

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.

但是,当我输入不正确的值,并关闭对话框(与右上角的关闭按钮),它验证文本框内容,并抛出了在MessageBox和形式不列入密切,因为我cacelling事件。

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)Initate验证处理程序:
从您要激活验证该控制的控制性能,双击此控件的事件列表中的验证事件。控制事件列表点击这个控件的属性表的事件(闪电看)工具栏按钮访问。然后,您可以在自动生成的处理程序与一个名字相结合的控制的名字,同时也是_Validating输入代码。这个处理程序,其中一些被确定为无效,可以通过添加'e.Cancel =真正的'指令强制有效条目的一部分。

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 =真正的'指令。这是当值被确定为无效。

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被执行验证之前点击事件。任何企图通过表单处理闭幕这样做是行不通的,因为它是那么为时已晚,一旦执行到达这样的处理程序。然而,X按钮的点击,可以迅速通过重写的WndProc()方法和测试一个'm.Msg == 0×10'的条件抓获。当该条件为真,以前引进的'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按钮应该取消valdations。然而,可以用来关闭窗体Esc键没有。当窗体的CancelButton属性用于该Esc键链接到表单的取消按钮,这样的Esc键被激活。

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)使ESC键也取消验证:

4) Make the escape key also cancel validation:

到X按钮类似,ESC键可以通过覆盖被EXISTINGMETHOD抓获。即ProcessDialogKey()方法。一时间越长,此前推出的'AutoValidate = AutoValidate.Disable;'指令可以用来禁用整体验证了ESC键也是如此。请参阅下面的代码的'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.

在这一点上,你应该做的!

At this point you should be done!

进一步考虑:

这是很好的注意到以下两种其他的方式来关闭该窗口也应该在这一点上正常工作。这两种方法是:

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天全站免登陆