Form.KeyPreview Свойство
Определение
Важно!
Некоторые сведения относятся к предварительной версии продукта, в которую до выпуска могут быть внесены существенные изменения. Майкрософт не предоставляет никаких гарантий, явных или подразумеваемых, относительно приведенных здесь сведений.
Возвращает или задает значение, указывающее, будет ли форма получать ключевые события перед передачей события в элемент управления с фокусом.
public:
property bool KeyPreview { bool get(); void set(bool value); };
public bool KeyPreview { get; set; }
member this.KeyPreview : bool with get, set
Public Property KeyPreview As Boolean
Значение свойства
true Значение , если форма получит все ключевые события; false Если выбранный в данный момент элемент управления в форме получает ключевые события. Значение по умолчанию — false.
Примеры
В следующем примере показано, как задать для свойства формы KeyPreview значение true и обрабатывать ключевые события на уровне формы. Чтобы запустить пример, вставьте следующий код в пустую форму.
using namespace System::Windows::Forms;
// This button is a simple extension of the button class that overrides
// the ProcessMnemonic method. If the mnemonic is correctly entered,
// the message box will appear and the click event will be raised.
// This method makes sure the control is selectable and the
// mnemonic is correct before displaying the message box
// and triggering the click event.
public ref class MyMnemonicButton: public Button
{
protected:
bool ProcessMnemonic( char inputChar )
{
if ( CanSelect && IsMnemonic( inputChar, this->Text ) )
{
MessageBox::Show( "You've raised the click event "
"using the mnemonic." );
this->PerformClick();
return true;
}
return false;
}
};
// Declare the controls contained on the form.
public ref class Form1: public System::Windows::Forms::Form
{
private:
MyMnemonicButton^ button1;
public private:
System::Windows::Forms::ListBox^ ListBox1;
public:
Form1()
: Form()
{
// Set KeyPreview object to true to allow the form to process
// the key before the control with focus processes it.
this->KeyPreview = true;
// Add a MyMnemonicButton.
button1 = gcnew MyMnemonicButton;
button1->Text = "&Click";
button1->Location = System::Drawing::Point( 100, 120 );
this->Controls->Add( button1 );
// Initialize a ListBox control and the form itself.
this->ListBox1 = gcnew System::Windows::Forms::ListBox;
this->SuspendLayout();
this->ListBox1->Location = System::Drawing::Point( 8, 8 );
this->ListBox1->Name = "ListBox1";
this->ListBox1->Size = System::Drawing::Size( 120, 95 );
this->ListBox1->TabIndex = 0;
this->ListBox1->Text = "Press a key";
this->ClientSize = System::Drawing::Size( 292, 266 );
this->Controls->Add( this->ListBox1 );
this->Name = "Form1";
this->Text = "Form1";
this->ResumeLayout( false );
// Associate the event-handling method with the
// KeyDown event.
this->KeyDown += gcnew KeyEventHandler( this, &Form1::Form1_KeyDown );
}
private:
// The form will handle all key events before the control with
// focus handles them. Show the keys pressed by adding the
// KeyCode object to ListBox1. Ensure the processing is passed
// to the control with focus by setting the KeyEventArg.Handled
// property to false.
void Form1_KeyDown( Object^ /*sender*/, KeyEventArgs^ e )
{
ListBox1->Items->Add( e->KeyCode );
e->Handled = false;
}
};
[System::STAThreadAttribute]
int main()
{
Application::Run( gcnew Form1 );
}
using System.Windows.Forms;
public class Form1 :
System.Windows.Forms.Form
// Declare the controls contained on the form.
{
private MyMnemonicButton button1;
internal System.Windows.Forms.ListBox ListBox1;
public Form1() : base()
{
// Set KeyPreview object to true to allow the form to process
// the key before the control with focus processes it.
this.KeyPreview = true;
// Add a MyMnemonicButton.
button1 = new MyMnemonicButton();
button1.Text = "&Click";
button1.Location = new System.Drawing.Point(100, 120);
this.Controls.Add(button1);
// Initialize a ListBox control and the form itself.
this.ListBox1 = new System.Windows.Forms.ListBox();
this.SuspendLayout();
this.ListBox1.Location = new System.Drawing.Point(8, 8);
this.ListBox1.Name = "ListBox1";
this.ListBox1.Size = new System.Drawing.Size(120, 95);
this.ListBox1.TabIndex = 0;
this.ListBox1.Text = "Press a key";
this.ClientSize = new System.Drawing.Size(292, 266);
this.Controls.Add(this.ListBox1);
this.Name = "Form1";
this.Text = "Form1";
this.ResumeLayout(false);
// Associate the event-handling method with the
// KeyDown event.
this.KeyDown += new KeyEventHandler(Form1_KeyDown);
}
// The form will handle all key events before the control with
// focus handles them. Show the keys pressed by adding the
// KeyCode object to ListBox1. Ensure the processing is passed
// to the control with focus by setting the KeyEventArg.Handled
// property to false.
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
ListBox1.Items.Add(e.KeyCode);
e.Handled = false;
}
[System.STAThreadAttribute]
public static void Main()
{
Application.Run(new Form1());
}
}
// This button is a simple extension of the button class that overrides
// the ProcessMnemonic method. If the mnemonic is correctly entered,
// the message box will appear and the click event will be raised.
public class MyMnemonicButton : Button
{
// This method makes sure the control is selectable and the
// mneumonic is correct before displaying the message box
// and triggering the click event.
protected override bool ProcessMnemonic(char inputChar)
{
if (CanSelect && IsMnemonic(inputChar, this.Text))
{
MessageBox.Show("You've raised the click event " +
"using the mnemonic.");
this.PerformClick();
return true;
}
return false;
}
}
Imports System.Windows.Forms
Imports System.Security.Permissions
Public Class Form1
Inherits System.Windows.Forms.Form
' Declare the controls contained on the form.
Private WithEvents button1 As MyMnemonicButton
Friend WithEvents ListBox1 As System.Windows.Forms.ListBox
Public Sub New()
MyBase.New()
' Set KeyPreview object to true to allow the form to process
' the key before the control with focus processes it.
Me.KeyPreview = True
' Add a MyMnemonicButton.
button1 = New MyMnemonicButton
button1.Text = "&Click"
button1.Location = New System.Drawing.Point(100, 120)
Me.Controls.Add(button1)
' Initialize a ListBox control and the form itself.
Me.ListBox1 = New System.Windows.Forms.ListBox
Me.SuspendLayout()
Me.ListBox1.Location = New System.Drawing.Point(8, 8)
Me.ListBox1.Name = "ListBox1"
Me.ListBox1.Size = New System.Drawing.Size(120, 95)
Me.ListBox1.TabIndex = 0
Me.ListBox1.Text = "Press a key"
Me.ClientSize = New System.Drawing.Size(292, 266)
Me.Controls.Add(Me.ListBox1)
Me.Name = "Form1"
Me.Text = "Form1"
Me.ResumeLayout(False)
End Sub
' The form will handle all key events before the control with
' focus handles them. Show the keys pressed by adding the
' KeyCode object to ListBox1. Ensure the processing is passed
' to the control with focus by setting the KeyEventArg.Handled
' property to false.
Private Sub Form1_KeyDown(ByVal sender As Object, _
ByVal e As KeyEventArgs) Handles MyBase.KeyDown
ListBox1.Items.Add(e.KeyCode)
e.Handled = False
End Sub
<System.STAThreadAttribute()> Public Shared Sub Main()
Application.Run(New Form1)
End Sub
End Class
' This button is a simple extension of the button class that overrides
' the ProcessMnemonic method. If the mnemonic is correctly entered,
' the message box will appear and the click event will be raised.
Public Class MyMnemonicButton
Inherits Button
' This method makes sure the control is selectable and the
' mneumonic is correct before displaying the message box
' and triggering the click event.
<System.Security.Permissions.UIPermission( _
System.Security.Permissions.SecurityAction.Demand, Window:=UIPermissionWindow.AllWindows)> _
Protected Overrides Function ProcessMnemonic( _
ByVal inputChar As Char) As Boolean
If (CanSelect And IsMnemonic(inputChar, Me.Text)) Then
MessageBox.Show("You've raised the click event " _
& "using the mnemonic.")
Me.PerformClick()
Return True
End If
Return False
End Function
End Class
Комментарии
Если для этого свойства задано trueзначение, форма получит все KeyPressсобытия KeyDownи KeyUp события. После завершения обработки нажатия клавиш обработчики событий формы затем назначаются элементу управления с фокусом. Например, если KeyPreview для свойства задано true значение и выбранный элемент управления в данный момент является элементом TextBoxуправления, после обработки нажатия клавиш обработчиками формы TextBox элемент управления получит клавишу, который был нажат. Чтобы обрабатывать события клавиатуры только на уровне формы и не разрешать элементам управления получать события клавиатуры, задайте KeyPressEventArgs.Handled для свойства в обработчике событий формы KeyPress значение true.
Это свойство можно использовать для обработки большинства нажатий клавиш в приложении и обработки нажатия клавиш или вызова соответствующего элемента управления для обработки нажатия клавиш. Например, если приложение использует ключи функций, может потребоваться обработать нажатия клавиш на уровне формы, а не писать код для каждого элемента управления, который может получать события нажатия клавиш.
Замечание
Если форма не имеет видимых или включенных элементов управления, она автоматически получает все события клавиатуры.
Замечание
Элемент управления в форме может быть запрограммирован для отмены любых получаемых нажатий клавиш. Так как элемент управления никогда не отправляет эти нажатия клавиш в форму, форма никогда не будет видеть их независимо от параметра KeyPreview.