G
G
Gina Lee2016-05-17 11:33:01
C++ / C#
Gina Lee, 2016-05-17 11:33:01

How can I make sure that ALL the buttons of a given form react in the same way if a certain condition is met?

I work with WinForms. It is required that if a certain character is entered in textbox1, when you click on any button, a message is displayed in the messagebox. whether it is possible to carry out it, not registering in EACH button_Click'e if with a condition on text check in textbox1?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Vitaly Pukhov, 2016-05-17
@Din7

when loading the form, it is enough to bind an event to a keystroke to all controls, but it is enough to write the handler once, an example is below. If the user entered F, then it is noted that F was pressed and when you click on any button on the form, "why did you write F, quickly erased it!" until the user erases it from the text field.

public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            foreach (Control item in this.Controls )
            {
                item.MouseClick += Item_MouseClick;
            }
        }

        private void Item_MouseClick(object sender, MouseEventArgs e)
        {
            if (keypressed)
            {
                if (textBox1.Text.Contains("ж"))
                {
                    MessageBox.Show("ты зачем написал Ж, быстро стер!");
                }
                else
                {
                    MessageBox.Show("Вот! другое дело!");
                    keypressed = false;
                }
                
            }
        }

        bool keypressed = false;
        private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar ==  'ж')
            {
                keypressed = true;
            }
        }
    }

D
Dmitry Kovalsky, 2016-05-17
@dmitryKovalskiy

As an option - to catch the state change event of the textBox. Clarify what the user actually entered. And if he entered the character you need - sequentially bind to all the buttons the event handler you need (at the same time, if necessary, untie the old handlers)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question