Шаг 5. Добавление обработчиков событий входа для элементов управления NumericUpDown Step 5: Add Enter Event Handlers for the NumericUpDown Controls
Эта статья относится к Visual Studio 2015. This article applies to Visual Studio 2015. Если вы ищете последние версии документации Visual Studio, используйте средство выбора версии в верхнем левом углу. If you’re looking for the latest Visual Studio documentation, use the version selector at the top left. Мы рекомендуем выполнить обновление до Visual Studio 2019. We recommend upgrading to Visual Studio 2019. Скачать эту версию можно здесь Download it here
В пятой части этого учебника вам предстоит добавить обработчики событий «Ввод», чтобы сделать ввод ответов на задачи головоломки немного удобнее. In the fifth part of this tutorial, you’ll add Enter event handlers to make entering answers for quiz problems a little easier. Этот код будет выделять и удалять текущее значение в каждом элементе управления NumericUpDown, как только игрок выберет элемент управления и начнет вводить другое значение. This code will select and clear the current value in each NumericUpDown control as soon as the quiz taker chooses it and starts to enter a different value.
Этот раздел входит в серию учебников, посвященных основам написания кода. This topic is part of a tutorial series about basic coding concepts. Обзор этого руководства см. в разделе учебник 2. Создание математической головоломки с течением времени. For an overview of the tutorial, see Tutorial 2: Create a Timed Math Quiz.
Проверка поведения по умолчанию To verify the default behavior
Запустите программу и запустите головоломку. Run your program, and start the quiz.
В элементе управления NumericUpDown для задачи сложения курсор мигает рядом с цифрой 0. In the NumericUpDown control for the addition problem, the cursor flashes next to 0 (zero).
Введите 3 и обратите внимание, что в элементе управления отображается 30. Enter 3 , and note that the control shows 30.
Введите 5 и обратите внимание, что появляется число 350, но через мгновение оно меняется на 100. Enter 5 , and note that 350 appears but changes to 100 after a second.
Перед исправлением ошибки подумайте, почему она возникла. Before you fix this problem, think about what’s happening. Подумайте, почему цифра 0 не исчезла, когда вы ввели 3 , и почему 350 меняется на 100, причем не сразу. Consider why the 0 didn’t disappear when you entered 3 and why 350 changed to 100 but not immediately.
Такое поведение может показаться странным, но оно полностью соответствует логике кода. This behavior may seem odd, but it makes sense given the logic of the code. При нажатии кнопки Запуск ее свойство Enabled принимает значение False, из-за чего кнопка становится недоступна и отображается серым цветом. When you choose the Start button, its Enabled property is set to False, and the button appears dimmed and is unavailable. Программа переводит текущее выделение (фокус) на элемент управления, имеющий следующее наименьшее значение TabIndex, т. е. элемент управления NumericUpDown для задачи сложения. Your program changes the current selection (focus) to the control that has the next lowest TabIndex value, which is the NumericUpDown control for the addition problem. Когда вы нажимаете клавишу TAB для перехода к элементу управления NumericUpDown, курсор автоматически помещается в начало элемента управления, поэтому вводимые цифры появляются слева, а не справа. When you use the Tab key to go to a NumericUpDown control, the cursor is automatically positioned at the start of the control, which is why the numbers that you enter appear from the left side and not the right side. При вводе числа, превышающего значение свойства MaximumValue (которому присвоено значение 100), введенное число заменяется значением этого свойства. When you specify a number that’s higher than the value of the MaximumValue property, which is set to 100, the number that you enter is replaced with the value of that property.
Добавление обработчика событий «Ввод» для элемента управления NumericUpDown To add an Enter event handler for a NumericUpDown control
Выберите первый элемент управления NumericUpDown (с именем sum) в форме, а затем в диалоговом окне Свойства выберите на панели инструментов значок События. Choose the first NumericUpDown control (named «sum») on the form, and then, in the Properties dialog box, choose the Events icon on the toolbar.
На вкладке События в диалоговом окне Свойства отображаются все события для выбранного в форме элемента, на которые можно реагировать (т. е. которые можно обрабатывать). The Events tab in the Properties dialog box displays all of the events that you can respond to (handle) for the item that you choose on the form. Поскольку выбран элемент управления NumericUpDown, все перечисленные события относятся к нему. Because you chose the NumericUpDown control, all of the events listed pertain to it.
Выберите событие Ввод, введите answer_Enter и нажмите клавишу ВВОД. Choose the Enter event, enter answer_Enter , and then choose the Enter key.
Диалоговое окно «Свойства»
Properties dialog box
Вы только что добавили обработчик событий «Ввод» для элемента управления NumericUpDown с именем «sum» и назвали этот обработчик answer_Enter. You’ve just added an Enter event handler for the sum NumericUpDown control, and you’ve named the handler answer_Enter.
В методе для обработчика событий answer_Enter добавьте следующий код. In the method for the answer_Enter event handler, add the following code.
Этот код может показаться сложным, однако в нем легко разобраться, если просмотреть его шаг за шагом. This code may look complex, but you can understand it if you look at it step by step. Сначала посмотрите на верхнюю часть метода — object sender в C# или sender As System.Object в Visual Basic. First, look at the top of the method: object sender in C# or sender As System.Object in Visual Basic. Этот параметр ссылается на объект, событие которого срабатывает. Он называется отправителем. This parameter refers to the object whose event is firing, which is known as the sender. В данном случае объектом-отправителем является элемент управления NumericUpDown. In this case, the sender object is the NumericUpDown control. Поэтому в первой строке метода указывается, что отправителем является не просто какой-либо объект, а именно элемент управления NumericUpDown. So, in the first line of the method, you specify that the sender isn’t just any generic object but specifically a NumericUpDown control. (Каждый элемент управления NumericUpDown является объектом, но не каждый объект является элементом управления NumericUpDown.) Элемент управления NumericUpDown называется answerBox в этом методе, так как он будет использоваться для всех элементов управления NumericUpDown в форме, а не только для элемента управления NumericUpDown. (Every NumericUpDown control is an object, but not every object is a NumericUpDown control.) The NumericUpDown control is named answerBox in this method, because it will be used for all of the NumericUpDown controls on the form, not just the sum NumericUpDown control. Поскольку переменная answerBox объявлена в этом методе, ее область действия ограничена этим методом. Because you declare the answerBox variable in this method, its scope applies only to this method. Иными словами, эту переменную можно использовать только внутри этого метода. In other words, the variable can be used only within this method.
В следующей строке кода выполняется проверка, что answerBox был успешно преобразован из объекта в элемент управления NumericUpDown. The next line verifies whether answerBox was successfully converted (cast) from an object to a NumericUpDown control. Если бы преобразование завершилось неудачей, переменная имела бы значение null (C#) или Nothing (Visual Basic). If the conversion was unsuccessful, the variable would have a value of null (C#) or Nothing (Visual Basic). Третья строка получает длину ответа, который отображается в элементе управления NumericUpDown, а четвертая строка выделяет текущее значение в элементе управления, основываясь на этой длине. The third line gets the length of the answer that appears in the NumericUpDown control, and the fourth line selects the current value in the control based on this length. Теперь, когда игрок выбирает элемент управления, Visual Studio запускает это событие, в результате чего текущий ответ выделяется. Now, when the quiz taker chooses the control, Visual Studio fires this event, which causes the current answer to be selected. Как только игрок начинает вводить другой ответ, предыдущий ответ удаляется и заменяется новым ответом. As soon as the quiz taker starts to enter a different answer, the previous answer is cleared and replaced with the new answer.
В конструкторе Windows Forms выберите элемент управления NumericUpDown с именем difference (разность). In Windows Forms Designer, choose the difference NumericUpDown control.
На странице События диалогового окна Свойства прокрутите вниз до события Ввод, щелкните направленную вниз стрелку в конце строки, а затем выберите обработчик событий answer_Enter , который вы только что добавили. In the Events page of the Properties dialog box, scroll down to the Enter event, choose the drop-down arrow at the end of the row, and then choose the answer_Enter event handler that you just added.
Повторите предыдущий шаг для элементов управления NumericUpDown с именами product и quotient (т. е. произведение и частное). Repeat the previous step for the product and quotient NumericUpDown controls.
Сохраните программу и запустите ее. Save your program, and then run it.
При выборе элемента управления NumericUpDown существующее значение автоматически выделяется и удаляется, когда вы начинаете вводить другое значение. When you choose a NumericUpDown control, the existing value is automatically selected and then cleared when you start to enter a different value.
Продолжить или повторить пройденный материал To continue or review
Чтобы перейти к следующему шагу руководства, см. Шаг 6. Добавление задачи на вычитание. To go to the next tutorial step, see Step 6: Add a Subtraction Problem.
Чтобы вернуться к предыдущему шагу руководства, см. Шаг 4. Добавление метода метода CheckTheAnswer (). To return to the previous tutorial step, see Step 4: Add the CheckTheAnswer() Method.
Control. Key Down Событие
Определение
Происходит при нажатии клавиши, если элемент управления имеет фокус. Occurs when a key is pressed while the control has focus.
Тип события
Примеры
В следующем примере кода событие используется KeyDown для определения типа символа, введенного в элемент управления. The following code example uses the KeyDown event to determine the type of character entered into the control.
В следующем примере кода демонстрируется порядок вызова KeyDown , KeyUp , KeyPress событий и регистрации обработчиков событий для них. The following code example demonstrates the order of raising the KeyDown, KeyUp, KeyPress events, and how to register event handlers on them.
Комментарии
Ключевые события происходят в следующем порядке: Key events occur in the following order:
Чтобы обрабатывать события клавиатуры только на уровне формы и не включать другие элементы управления для получения событий клавиатуры, задайте KeyPressEventArgs.Handled для свойства в KeyPress методе обработки событий формы значение true . To handle keyboard events only at the form level and not enable other controls to receive keyboard events, set the KeyPressEventArgs.Handled property in your form’s KeyPress event-handling method to true . Некоторые клавиши, такие как TAB, RETURN, ESC и клавиши со стрелками, автоматически обрабатываются элементами управления. Certain keys, such as the TAB, RETURN, ESC, and arrow keys are handled by controls automatically. Чтобы эти ключи вызывали KeyDown событие, необходимо переопределить IsInputKey метод в каждом элементе управления в форме. To have these keys raise the KeyDown event, you must override the IsInputKey method in each control on your form. Код переопределения должен IsInputKey определить, нажата ли одна из специальных клавиш, и возвращать значение true . The code for the override of the IsInputKey would need to determine if one of the special keys is pressed and return a value of true . Вместо переопределения IsInputKey метода можно выполнить обработку PreviewKeyDown события и присвоить IsInputKey свойству значение true . Instead of overriding the IsInputKey method, you can handle the PreviewKeyDown event and set the IsInputKey property to true . Пример кода см. в описании PreviewKeyDown события. For a code example, see the PreviewKeyDown event.
Дополнительные сведения об обработке событий см. в разделе обработка и вызов событий. For more information about handling events, see Handling and Raising Events.
Шаг 4. Добавление обработчика событий Click к каждому элементу управления Label Step 4: Add a click event handler to each label
Игра «Подбери пару!» работает следующим образом. The matching game works as follows:
Когда игрок выбирает один из квадратов со скрытым значком, программа показывает значок игроку, изменяя цвет значка на черный. When a player chooses one of the squares with a hidden icon, the program shows the icon to the player by changing the icon color to black.
После этого игрок выбирает другой скрытый значок. Then the player chooses another hidden icon.
Если значки совпадают, они остаются видимыми. If the icons match, they stay visible. Если нет, оба значка снова скрываются. If not, both icons are hidden again.
Чтобы программа работала именно так, добавьте обработчик событий Click, изменяющий цвет выбираемого элемента управления Label. To get your program to work that way, you add a Click event handler that changes the color of the label that is chosen.
Добавление обработчика событий Click к каждому элементу управления Label To add a click event handler to each label
Откройте форму в конструкторе Windows Forms. Open the form in the Windows Forms Designer. В обозревателе решений выберите Form1.cs или Form1.vb. In Solution Explorer, choose Form1.cs or Form1.vb. В строке меню выберите Вид > Конструктор. On the menu bar, choose View > Designer.
Выберите первый элемент Label, чтобы выделить его. Choose the first label control to select it. Затем, удерживая нажатой клавишу CTRL, выберите каждую из оставшихся меток. Then, hold down the Ctrl key while you choose each of the other labels to select them. Убедитесь, что выбраны все метки. Be sure that every label is selected.
Нажмите кнопку События на панели инструментов в окне Свойства, чтобы открыть страницу События в окне Свойства. Choose the Events button on the tool bar in the Properties window to view the Events page in the Properties window. Прокрутите вниз до события Click и введите label_Click в поле, как показано на следующем снимке экрана. Scroll down to the Click event, and enter label_Click in the box, as shown in the following screenshot.
Нажмите клавишу ВВОД. Choose the Enter key. Интегрированная среда разработки добавит обработчик событий Click , который называется label_Click() , в код и подключит его к каждому элементу управления Label в форме. The IDE adds a Click event handler called label_Click() to the code, and hooks it to each of the labels on the form.
Добавьте остальную часть кода следующим образом: Fill in the rest of the code, as follows:
Используйте элемент управления языка программирования в правом верхнем углу этой страницы, чтобы просмотреть фрагмент кода на C# или Visual Basic. Use the programming language control at the top right of this page to view either the C# code snippet or the Visual Basic code snippet.
При копировании и вставке блока кода label_Click() вместо его ввода вручную проследите за тем, что заменить существующий код label_Click() . If you copy and paste the label_Click() code block rather than entering the code manually, be sure to replace the existing label_Click() code. В противном случае в коде появится дублирующий блок. Otherwise, you’ll end up with a duplicate code block.
Возможно, вы узнали object sender в верхней части обработчика событий; он совпадает с кодом в разделе Руководство 2. Создание ограниченной по времени математической головоломки. You may recognize object sender at the top of the event handler as the same one used in the Tutorial 2: Create a timed math quiz tutorial. Так как вы подключили разные события Click элемента управления Label к одному методу обработчика событий, один и тот же метод вызывается независимо от того, какой элемент управления Label щелкнет пользователь. Because you hooked up different label control click events to a single event handler method, the same method is called no matter which label the user chooses. Методу обработчика событий необходимо знать, какой элемент управления Label выбрал игрок, поэтому для его определения используется имя sender . The event handler method needs to know which label was chosen, so it uses the name sender to identify the label control. Первая строка метода сообщает программе, что это не просто универсальный объект, а элемент управления Label, для обращения к свойствам и методам которого используется имя clickedLabel . The first line of the method tells the program that it’s not just a generic object, but specifically a label control, and that it uses the name clickedLabel to access the label’s properties and methods.
Этот метод сначала проверяет, было ли успешно выполнено преобразование (приведение) clickedLabel из объекта в элемент управления Label. This method first checks whether clickedLabel was successfully converted (cast) from an object to a label control. Если операция завершилась неудачно, его значение будет null (C#) или Nothing (Visual Basic) и оставшаяся часть кода метода не будет выполнена. If unsuccessful, it has a value of null (C#) or Nothing (Visual Basic), and you don’t want to execute the remainder of the code in the method. Затем метод с помощью свойства ForeColor элемента управления Label проверяет цвет текста выбранной метки. Next, the method checks the chosen label’s text color by using the label’s ForeColor property. Если цвет текста метки черный, это это означает, что значок уже был выбран, а метод выполнен. If the label’s text color is black, then that means the icon’s already been chosen and the method is done. (Для этого и нужен оператор return . Он сообщает программе, что требуется остановить выполнение метода.) В противном случае значок не был выбран, поэтому программа изменяет цвет текста метки на черный. (That’s what the return statement does: It tells the program to stop executing the method.) Otherwise, the icon hasn’t been chosen, so the program changes the label’s text color to black.
В строке меню выберите Файл > Сохранить все, чтобы сохранить ход выполнения, а затем в строке меню выберите Отладка > Начать отладку, чтобы запустить программу. On the menu bar, choose File > Save All to save your progress, and then, on the menu bar, choose Debug > Start Debugging to run your program. Вы должны увидеть пустую форму с синим фоном. You should see an empty form with a blue background. Выберите любую ячейку в форме, и один из значков станет видимым. Choose any of the cells in the form, and one of the icons should become visible. Продолжайте выбирать различные ячейки формы. Continue choosing different places in the form. Значки будут отображаться при их выборе. As you choose the icons, they should appear.
Продолжить или повторить пройденный материал To continue or review
Следующий раздел руководства: Шаг 5. Добавление ссылок на элементы управления Label . To go to the next tutorial step, see Step 5: Add label references.