Key Event Args. Handled Свойство
Некоторые сведения относятся к предварительной версии продукта, в которую до выпуска могут быть внесены существенные изменения. Майкрософт не предоставляет никаких гарантий, явных или подразумеваемых, относительно приведенных здесь сведений.
Возвращает или задает значение, указывающее, было ли обработано событие.
public: property bool Handled < bool get(); void set(bool value); >;
public bool Handled
member this.Handled : bool with get, set
Public Property Handled As Boolean
Значение свойства
Значение true для обхода обработки элемента управления по умолчанию; значение false для передачи события обработчику элементов управления по умолчанию.
Примеры
В следующем примере определяется, нажал ли пользователь нечисловую клавишу, и если да, событие отменяется KeyPress с помощью Handled свойства .
// Boolean flag used to determine when a character other than a number is entered. private: bool nonNumberEntered; // Handle the KeyDown event to determine the type of character entered into the control. void textBox1_KeyDown( Object^ /*sender*/, System::Windows::Forms::KeyEventArgs^ e ) < // Initialize the flag to false. nonNumberEntered = false; // Determine whether the keystroke is a number from the top of the keyboard. if ( e->KeyCode < Keys::D0 || e->KeyCode > Keys::D9 ) < // Determine whether the keystroke is a number from the keypad. if ( e->KeyCode < Keys::NumPad0 || e->KeyCode > Keys::NumPad9 ) < // Determine whether the keystroke is a backspace. if ( e->KeyCode != Keys::Back ) < // A non-numerical keystroke was pressed. // Set the flag to true and evaluate in KeyPress event. nonNumberEntered = true; >> > //If shift key was pressed, it's not a number. if (Control::ModifierKeys == Keys::Shift) < nonNumberEntered = true; >> // This event occurs after the KeyDown event and can be used to prevent // characters from entering the control. void textBox1_KeyPress( Object^ /*sender*/, System::Windows::Forms::KeyPressEventArgs^ e ) < // Check for the flag being set in the KeyDown event. if ( nonNumberEntered == true ) < // Stop the character from being entered into the control since it is non-numerical. e->Handled = true; > >
// Boolean flag used to determine when a character other than a number is entered. private bool nonNumberEntered = false; // Handle the KeyDown event to determine the type of character entered into the control. private void textBox1_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e) < // Initialize the flag to false. nonNumberEntered = false; // Determine whether the keystroke is a number from the top of the keyboard. if (e.KeyCode < Keys.D0 || e.KeyCode >Keys.D9) < // Determine whether the keystroke is a number from the keypad. if (e.KeyCode < Keys.NumPad0 || e.KeyCode >Keys.NumPad9) < // Determine whether the keystroke is a backspace. if(e.KeyCode != Keys.Back) < // A non-numerical keystroke was pressed. // Set the flag to true and evaluate in KeyPress event. nonNumberEntered = true; >> > //If shift key was pressed, it's not a number. if (Control.ModifierKeys == Keys.Shift) < nonNumberEntered = true; >> // This event occurs after the KeyDown event and can be used to prevent // characters from entering the control. private void textBox1_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e) < // Check for the flag being set in the KeyDown event. if (nonNumberEntered == true) < // Stop the character from being entered into the control since it is non-numerical. e.Handled = true; >>
' Boolean flag used to determine when a character other than a number is entered. Private nonNumberEntered As Boolean = False ' Handle the KeyDown event to determine the type of character entered into the control. Private Sub textBox1_KeyDown(sender As Object, e As System.Windows.Forms.KeyEventArgs) _ Handles textBox1.KeyDown ' Initialize the flag to false. nonNumberEntered = False ' Determine whether the keystroke is a number from the top of the keyboard. If e.KeyCode < Keys.D0 OrElse e.KeyCode >Keys.D9 Then ' Determine whether the keystroke is a number from the keypad. If e.KeyCode < Keys.NumPad0 OrElse e.KeyCode >Keys.NumPad9 Then ' Determine whether the keystroke is a backspace. If e.KeyCode <> Keys.Back Then ' A non-numerical keystroke was pressed. ' Set the flag to true and evaluate in KeyPress event. nonNumberEntered = True End If End If End If 'If shift key was pressed, it's not a number. If Control.ModifierKeys = Keys.Shift Then nonNumberEntered = true End If End Sub ' This event occurs after the KeyDown event and can be used ' to prevent characters from entering the control. Private Sub textBox1_KeyPress(sender As Object, e As System.Windows.Forms.KeyPressEventArgs) _ Handles textBox1.KeyPress ' Check for the flag being set in the KeyDown event. If nonNumberEntered = True Then ' Stop the character from being entered into the control since it is non-numerical. e.Handled = True End If End Sub
Комментарии
Handledреализуется по-разному различными элементами управления в Windows Forms. Для таких элементов управления, как TextBox собственные элементы управления Win32 подкласса, это интерпретируется как означает, что ключевое сообщение не должно передаваться в базовый собственный элемент управления. Если для этого элемента управления задано Handled значение true TextBox, нажатие клавиши events не будет передаваться базовому элементу управления «Текстовое поле Win32», но он по-прежнему будет отображать символы, введенные пользователем.
Если вы хотите запретить текущему элементу управления получать нажатие клавиши SuppressKeyPress , используйте свойство .
Применяется к
См. также раздел
Key Press Event Args. Handled Свойство
Некоторые сведения относятся к предварительной версии продукта, в которую до выпуска могут быть внесены существенные изменения. Майкрософт не предоставляет никаких гарантий, явных или подразумеваемых, относительно приведенных здесь сведений.
Возвращает или задает значение, показывающее, было ли обработано событие KeyPress.
public: property bool Handled < bool get(); void set(bool value); >;
public bool Handled
member this.Handled : bool with get, set
Public Property Handled As Boolean
Значение свойства
Значение true , если событие обработано; в противном случае — значение false .
Примеры
В следующем примере создается TextBox элемент управления . Метод keypressed использует свойство , KeyChar чтобы проверка, нажата ли клавиша ВВОД. Если нажата клавиша ВВОД, свойству Handled присваивается значение true , указывающее, что событие обработано.
#using #using #using using namespace System; using namespace System::Windows::Forms; public ref class Form1: public Form < public: Form1() < // Create a TextBox control. TextBox^ tb = gcnew TextBox; this->Controls->Add( tb ); tb->KeyPress += gcnew KeyPressEventHandler( this, &Form1::keypressed ); > private: void keypressed( Object^ /*o*/, KeyPressEventArgs^ e ) < // The keypressed method uses the KeyChar property to check // whether the ENTER key is pressed. // If the ENTER key is pressed, the Handled property is set to true, // to indicate the event is handled. if ( e->KeyChar == (char)13 ) e->Handled = true; > >; int main()
using System; using System.Windows.Forms; public class Form1: Form < public Form1() < // Create a TextBox control. TextBox tb = new TextBox(); this.Controls.Add(tb); tb.KeyPress += new KeyPressEventHandler(keypressed); >private void keypressed(Object o, KeyPressEventArgs e) < // The keypressed method uses the KeyChar property to check // whether the ENTER key is pressed. // If the ENTER key is pressed, the Handled property is set to true, // to indicate the event is handled. if (e.KeyChar == (char)Keys.Return) < e.Handled = true; >> public static void Main() < Application.Run(new Form1()); >>
Imports System.Windows.Forms Public Class Form1 Inherits Form Public Sub New() ' Create a TextBox control. Dim tb As New TextBox() Me.Controls.Add(tb) AddHandler tb.KeyPress, AddressOf keypressed End Sub Private Sub keypressed(ByVal o As [Object], ByVal e As KeyPressEventArgs) ' The keypressed method uses the KeyChar property to check ' whether the ENTER key is pressed. ' If the ENTER key is pressed, the Handled property is set to true, ' to indicate the event is handled. If e.KeyChar = Microsoft.VisualBasic.ChrW(Keys.Return) Then e.Handled = True End If End Sub Public Shared Sub Main() Application.Run(New Form1()) End Sub End Class
Комментарии
Если событие не обработано, оно будет отправлено в операционную систему для обработки по умолчанию. Задайте значение Handled , true чтобы отменить KeyPress событие.
Textbox ввод только цифр
Из этой небольшой статьи вы узнаете, как разрешить ввод только цифр в элемент управления Textbox.
1. Выбираем элемент управления textbox и подписываемся на событие KeyPress.
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
2. Воспользуемся свойством KeyChar, параметра e, чтобы получить введенный в текстовое поле символ.
e.KeyChar
3. С помощью статического метода IsDigit класса Char определим, является ли введенный символ цифрой.
private void textBox1_KeyPress(object sender, KeyPressEventArgs e) < if (Char.IsDigit(e.KeyChar)) < //это цифра! >>
4. Разрешим вводить в textbox только цифры, установив для свойства Handled, всё того же параметра e, значение true.
private void textBox1_KeyPress(object sender, KeyPressEventArgs e) < if (Char.IsDigit(e.KeyChar)) < >else < e.Handled = true; >>
5. В окне Properties установим для свойства ShortcutsEnabled значение true. Тем самым запретим ввод любых данных с помощью сочетания клавиш: Ctrl+C (копировать) и Ctrl+V (вставить).

- Включаем нумерацию строк в Visual Studio 2013
- Добавление строки в Excel файл
- Определение дня недели по дате
Что такое HANDLE в программировании под windows?
Что такое HANDLE? Я начал путать его с контекстом устройства. Но что-то мне подсказывает, что это разные вещи.
Отслеживать
32.1k 19 19 золотых знаков 79 79 серебряных знаков 106 106 бронзовых знаков
задан 16 ноя 2014 в 12:48
10k 14 14 золотых знаков 53 53 серебряных знака 118 118 бронзовых знаков
3 ответа 3
Сортировка: Сброс на вариант по умолчанию
HANDLE — дескриптор, т.е. число, с помощью которого можно идентифицировать ресурс. С помощью дескприторов можно ссылаться на окна, объекты ядра, графические объекты и т.п.
Можно провести аналогию с массивом: у нас имеется набор ресурсов, а HANDLE — это индекс, который указывает на конкретный ресурс. Это все, конечно, абстрактно, но думаю идея понятна.
Отслеживать
ответ дан 16 ноя 2014 в 21:01
skubarenko skubarenko
2,680 2 2 золотых знака 14 14 серебряных знаков 25 25 бронзовых знаков
Я бы еще добавил, что HANDLE — это такой отдаленный аналог указателя на некий ресурс.
17 ноя 2014 в 8:32
Угу. Opaque pointer. То есть ссылка на объект (число, по которому ядро может идентифицировать объект), но не обязательно адрес. Может быть индексом во внутренней таблице, нативным указателем, в котором некоторые биты используются «не по назначению» или с несколькими специальными значениями, чем угодно.
17 ноя 2014 в 21:27
Вы не работаете с контекстом устройства напрямую. Сам по себе контекст устройства — «черный ящик», что у него внутри, мы не знаем. У контекста устройства есть хэндл (идентификатор), который, например, возвращают функции CreateDC и GetDC и который можно передать в другие WinAPI функции.
Получается, контекст устройства (DC) — некий сложный объект, а хэндл контекста устройства (hDC) — число. Хэндл контекста устройства — это один из видов (частный случай) хэндлов. Кроме хэндлов DC, есть хэндлы окон, файлов, битмэпов, всяких кистей/карандашей и т.д.