Click here to Skip to main content
15,885,546 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
I am creating a Piano Application with all the keys as buttons.

It works when i click the Piano button using mouse click.

Now, I want the same event to occur when i press a key in the keyboard.
What event should I use ?

This is the event for the button click
C#
private void button1_Click(object sender, EventArgs e)
        {
            MessageBox.Show("A");
            Beep(349, 150);

        }


Now I want the same process to happen when i click the "A" key in my keyboard.
I know its some event. But I couldn't find it.
How should I proceed to achieve it ? And how should i implement it ?

Thanks in advance
Posted
Updated 26-Jul-13 2:03am
v3
Comments
[no name] 26-Jul-13 8:11am    
You could not find the KeyDown event?
Divakar Raj M 26-Jul-13 8:14am    
i added this code, but it didnt work

private void Form1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyData==Keys.A)
{
MessageBox.Show("Done");
}
}

1 solution

You have form? Create the KeyDown[^] Event.

From http://stackoverflow.com/a/3334956[^]

C#
public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        this.BringToFront();
        this.Focus();
        this.KeyPreview = true;
        this.KeyDown += new KeyEventHandler(Form1_KeyDown);
        
    }

    void Form1_KeyDown(object sender, KeyEventArgs e)
    {
        Console.WriteLine("test");
    }
 
Share this answer
 
v3
Comments
Divakar Raj M 26-Jul-13 8:19am    
This works. But makes the event run twice. Any idea why ?
Sushil Mate 26-Jul-13 8:20am    
you have already created event in the from designer?
Sushil Mate 26-Jul-13 8:21am    
try update one.
Divakar Raj M 26-Jul-13 8:22am    
I used KeyPress event and it works.. Thanks !! :)
Sushil Mate 26-Jul-13 8:22am    
great.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900