Click here to Skip to main content
15,893,487 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
How do I check whether the 'Enter' key on the keyboard is pressed (or any other key for that matter) and if it has, perform some code?
Posted
Updated 29-Jan-12 19:48pm
v2
Comments
Rajesh Anuhya 30-Jan-12 2:54am    
Winforms or webforms??
--RA

 
Share this answer
 
use keydown handler


C#
this.KeyDown+= new KeyEventHandler(CallMeOnAnyKeyPress)


void CallMeOnAnyKeyPress(object sender,KeyEventArgs e)
{
if(e.KeyValue==13)
// any1 below will also do :-
// if(e.KeyData=Keys.Enter)
//if(e.keyCode==Keys.Enter)
//if(e.KeyData==Keys.Enter)
{
MessageBox.Show("you pressed enter");
}
}
 
Share this answer
 
v2
Quote:
<script type="text/javascript">



function CheckKeyPressed(elmnt,e)
{
e = e || window.event;
ch = e.which || e.keyCode;
if (ch ==13 || ch == 9)
{
alert("Enter key Pressed");
}


}


</script>



<asp:textbox onkeydown=" return isNumeric(this, event);" id="Text1" runat="server" xmlns:asp="#unknown">
 
Share this answer
 
C#
//--------------------------------------
this.[ControlName].KeyPress += new System.Windows.Forms.KeyPressEventHandler(CheckKeys); //for adding the KeyPress event to a specific control
//--------------------------------------

//--------------------------------------
// new CheckKeys method
private void CheckKeys(object sender, System.Windows.Forms.KeyPressEventArgs e)
                {
                        if (e.KeyChar == (char)13)
                        {
                           // Then the code you want to take place on Enter Press
                        }
                }
//-------------------------------------
 
Share this answer
 
hi,

you can try this

C#
 <script type="text/javascript" language="javascript">
if (window.captureEvents) {
    window.captureEvents(Event.KeyUp);
    window.onkeyup = executeCode;
}
else if (window.attachEvent) {
    document.attachEvent('onkeyup', executeCode);
}

function executeCode(evt) {
    if (evt == null) {
        evt = window.event;
    }
    var theKey = parseInt(evt.keyCode, 10);
    switch (theKey) {
        case 113:  // F2
            document.getElementById('button1').click();
            break;
        case 119:  // F8
            document.getElementById('button2').click();
            break;
        case 120:  // F9
            document.getElementById('button3').click();
            break;
        case 87: //w
            if (window.event.altKey)
                document.getElementById('button4').click();
            break;
    }
    evt.returnValue = false;
    return false;
}
</script>
 
Share this answer
 

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