首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

C# 處理滑鼠與鍵盤事件(三):鍵盤事件 KeyDown/KeyUp/KeyPress 完整實作

     編輯:關於C語言

鍵盤相關三大事件

  • KeyDown、KeyUp:委派 KeyEventHandler,事件引數 KeyEventArgs
  • KeyPress:委派 KeyPressEventHandler,事件引數 KeyPressEventArgs

皆位於 System.Windows.Forms 命名空間。

事件訂閱語法

// KeyDown / KeyUp
button1.KeyUp += new KeyEventHandler(button1_KUp);

private void button1_KUp(object sender, KeyEventArgs e)
{
    // 處理邏輯
}

// KeyPress
button1.KeyPress += new KeyPressEventHandler(button1_KPress);

private void button1_KPress(object sender, KeyPressEventArgs e)
{
    // 處理邏輯
}

典型應用:判斷按下哪個鍵

KeyEventArgs.KeyCode 屬性可取得實體鍵碼。於 KeyUp 或 KeyDown 處理。

完整範例:key.cs

using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;

public class Form1 : Form
{
    private Container components = null;

    public Form1()
    {
        InitializeComponent();
    }

    protected override void Dispose(bool disposing)
    {
        if (disposing && components != null) components.Dispose();
        base.Dispose(disposing);
    }

    private void InitializeComponent()
    {
        AutoScaleBaseSize = new Size(6, 14);
        ClientSize = new Size(292, 273);
        Name = "Form1";
        Text = "C# 處理鍵盤事件!";
        KeyUp += new KeyEventHandler(Form1_KeyUp);
    }

    static void Main() { Application.Run(new Form1()); }

    private void Form1_KeyUp(object sender, KeyEventArgs e)
    {
        MessageBox.Show(e.KeyCode.ToString(), "您所按下的鍵為:");
    }
}

執行畫面

圖02:用 C# 讀取鍵盤按鍵的程式執行介面

總結

本文介紹 C# 定義滑鼠/鍵盤事件與典型處理方式。雖屬基礎,但實務上最常用,掌握後可舉一反三解決更多問題。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved