Search code examples
c#messageboxenterkeyup

MessageBox doesn't close when I use KeyUp event


My form has one textbox for input, listview for save.

User input number in textbox, and input enter, program check input number length and duplication

  1. textbox KeyUp Event

    private void txb_MList_num_KeyUp(object sender, KeyEventArgs e)
    {
        if (e.KeyCode == Keys.Enter)
        {
            if (check_MList_dup())
            {
                lstv_MList.Items.Add(txb_MList_num.Text);
                allList.Add(txb_MList_num.Text);
                txb_MList_num.Text = "";
            }
        }
    }
    
  2. check_MList_dup()

    private bool check_MList_dup()
    {
        bool OK = true;
        if (txb_MList_num.TextLength < 11)
        {
            MessageBox.Show("Input more text(length = 11)");
            return false;
        }
        else
        {
            for (int i = 0; i < allList.Count; i++)
                if (allList[i].Equals(txb_MList_num.Text))
                {
                    MessageBox.Show("It's duplication.");
                    return false;
                }
        }
        return OK;
    }
    

But User input enter for close MessageBox, program show MessageBox again, again...before using mouse.

I debug it use breakpoint, event is not occuer when MessageBox is showing.

But delete breakpoint, MessageBox is repeated.

I use e.KeyCode == Keys.Enter && this.Focused

but this.Focused always return false .

How can I close MessageBox?


Solution

  • You can try and use txb_MList_num.KeyDown event

    As per MSDN:-

    "KeyDown event Occurs when a key is pressed while the control has focus."