Form.KeyPreview 属性

定义

获取或设置一个值,该值指示在将键事件传递到具有焦点的控件前,窗体是否将接收此键事件。Gets or sets a value indicating whether the form will receive key events before the event is passed to the control that has focus.

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;如果窗体上当前选定控件接收键事件,则为 falsetrue if the form will receive all key events; false if the currently selected control on the form receives key events. 默认值为 falseThe default is false.

示例

下面的示例演示如何将窗体的 KeyPreview 属性设置为 true,并在窗体级别处理键事件。The following example demonstrates setting a form's KeyPreview property to true and handling the key events at the form level. 若要运行该示例,请将以下代码粘贴到空白窗体中。To run the example, paste the following code in a blank form.

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;
using System.Security.Permissions;

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.
{
    [UIPermission(
        SecurityAction.Demand, Window = UIPermissionWindow.AllWindows)]
        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",则窗体将接收所有 KeyPressKeyDownKeyUp 事件。When this property is set to true, the form will receive all KeyPress, KeyDown, and KeyUp events. 在窗体的事件处理程序处理完击键后,会将击键分配给具有焦点的控件。After the form's event handlers have completed processing the keystroke, the keystroke is then assigned to the control with focus. 例如,如果将 KeyPreview 属性设置为 true 并且当前选定的控件是 TextBox,则在由该窗体的事件处理程序处理击键后,TextBox 控件将接收所按下的键。For example, if the KeyPreview property is set to true and the currently selected control is a TextBox, after the keystroke is handled by the event handlers of the form the TextBox control will receive the key that was pressed. 若要仅在窗体级别处理键盘事件,而不允许控件接收键盘事件,请将窗体的 KeyPress 事件处理程序中的 KeyPressEventArgs.Handled 属性设置为 trueTo handle keyboard events only at the form level and not allow controls to receive keyboard events, set the KeyPressEventArgs.Handled property in your form's KeyPress event handler to true.

您可以使用此属性来处理应用程序中的大多数击键,并处理击键或调用相应的控件来处理击键。You can use this property to process most keystrokes in your application and either handle the keystroke or call the appropriate control to handle the keystroke. 例如,当应用程序使用函数键时,您可能希望在窗体级别处理击键,而不是为可能接收击键事件的每个控件都编写代码。For example, when an application uses function keys, you might want to process the keystrokes at the form level rather than writing code for each control that might receive keystroke events.

备注

如果窗体没有可见或启用的控件,则它会自动接收所有键盘事件。If a form has no visible or enabled controls, it automatically receives all keyboard events.

备注

可以对窗体上的控件进行编程以取消其收到的任何击键。A control on a form may be programmed to cancel any keystrokes it receives. 由于控件永远不会将这些键击发送到窗体,因此窗体将永远不会看到它们,而不管 KeyPreview的设置。Since the control never sends these keystrokes to the form, the form will never see them regardless of the setting of KeyPreview.

适用于

另请参阅