\

Facebook


วันอังคารที่ 1 ตุลาคม พ.ศ. 2556

[WinForm C#] Basic Keyboard Reader

Almost of any software which have builded for user's comfortable have special shortcut keys, so today i would like to present easy WinForm keys reader.

In Winform c#, which interite from base Form of Windows.system also include reading key method. just create new project call "ReadKeyBoard" and add new main class call "Form1". Then, in properties tab click on Events button to reveal all form's event inside and double click on "KeyDown" event to active usage.


Let's see inside "Form1_KeyDown" method, it accepts two parameter which one is Object and another one is KeyEventArg e. So anytime you press Keyboard and take key up, program should automatically detect on "what key you press" and send it into method with e value. For example, i press "Backspace", i should get valuse as Keys.Back.

For combination keys such as CTRL + C, SHIFT + F4, you should get 2 values while taking inside this method. One modify key and one normal key, so make sure you have check for specific case. Just like combine Ctrl + C = copy :

if (e.Modifiers == Keys.Control && e.KeyCode == Keys.C)
            {
                // Do Copy stuff
            }

For normal key only :

 else  if (e.KeyCode == Keys.Space)
            {
                // Do your stuff
            }

Write other conditions as you want. i post the code example below. Have a nice day with less bug. Thank for interesting.


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace CombineKey
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Modifiers == Keys.Control && e.KeyCode == Keys.C)
            {
                textBox1.Text = "Control + C";
            }
            else if (e.KeyCode == Keys.Back)
            {
                textBox1.Text = "Back";
            }
            else  if (e.KeyCode == Keys.Space)
            {
                textBox1.Text = "Space Bar";
            }
            else if (e.KeyCode == Keys.F4)
            {
                textBox1.Text = "F4";
            }
            else if (e.KeyCode == Keys.Tab)
            {
                textBox1.Text = "Tab";
            }
            else
            {
                textBox1.Text = "None";
            }
        }
    }
}

May be like this posts