//================================================================================================= // C#で作るイベントの基本(キー入力編) // キーを入力したとき、それに対応した文字が表示されるプログラム。 // キーイベントの場合、ハンドル登録時にはEventHandlerではなく「KeyEventHandler」を使用する。 // イベントを受け取り処理する関数の引数もEventArgsではなく「KeyEventArgs」となる。 // // 参考文献:やさしいC#(p158) // 2012/11/12/オワタ //================================================================================================= using System; using System.Windows.Forms; class KeyEvent : Form { //< ラベル * 2 private Label[] mLabel = new Label[2]; //< メイン関数 public static void Main() { Application.Run(new KeyEvent()); } public KeyEvent() { //< Window生成 設定 this.Text = "キー入力"; this.Width = 250; this.Height = 100; //< ラベル設定 mLabel[0] = new Label(); mLabel[0].Text = "矢印キーで選びなさい"; mLabel[0].Width = this.Width; //< ラベル設定(初期は未表示、ボタンを押したら表示する) mLabel[1] = new Label(); mLabel[1].Width = this.Width; mLabel[1].Top = mLabel[0].Bottom; //< Windowと同期 mLabel[0].Parent = this; mLabel[1].Parent = this; //< キーイベントハンドル設定 this.KeyDown += new KeyEventHandler(formKeyDown); } //< キーを押した時に処理されるキーイベント関数 public void formKeyDown(Object obj, KeyEventArgs e) { string str = ""; switch (e.KeyCode) { case Keys.Up: //< 上キー入力 str = "上キー"; break; case Keys.Down: //< 下キー入力 str = "下キー"; break; case Keys.Right: //< 右キー入力 str = "右キー"; break; case Keys.Left: //< 左キー入力 str = "左キー"; break; default: str = "その他のキー"; break; } //< テキスト表示 mLabel[1].Text = str + "を押したね。"; } };