Click here to Skip to main content
15,886,067 members
Please Sign up or sign in to vote.
3.00/5 (2 votes)
See more:
Hello friends i have to validate my windows application input filed with string or number or any other thing..

now i have almost done this but now i have an question is that how to detect that the key pressed by user is pressed with the shift key or not..?

means for inputting "(" bracket we have to press shift key + 9 key on keyboard

so i want to check like this any key is pressed with shift key or not..
Posted
Comments
Sergey Alexandrovich Kryukov 26-Sep-11 2:43am    
Tag it: WPF, Forms, what?
--SA
Sergey Alexandrovich Kryukov 26-Sep-11 2:53am    
Visual Studio help broken?
--SA

Try this one


XML
<script type="text/javascript">
function isKeyPressed(event){
    if (event.shiftKey==1){
        alert("The shift key was pressed!")
    }else{
        alert("The shift key was NOT pressed!")
    }
}

</script>



or

XML
<script type="text/javascript">
function detectspecialkeys(e){
var evtobj=window.event? event : e
if (evtobj.shiftKey)
alert("you pressed the 'Shift' keys")
}
document.onkeypress=detectspecialkeys
</script>
 
Share this answer
 
v2
It's a shame you did not specify UI library. What, do I need to give you answers for all cases?

For WPF, use event arguments of the event, take the property KeyboardDevice, its type has a method System.Windows.Input.KeyboardDevice.GetKeyStates which will return a state of any key.

See:
http://msdn.microsoft.com/en-us/library/system.windows.input.keyeventargs.aspx[^],
http://msdn.microsoft.com/en-us/library/system.windows.input.keyboarddevice.getkeystates.aspx[^],
http://msdn.microsoft.com/en-us/library/system.windows.input.keyboardeventargs.keyboarddevice.aspx[^].

For Forms, use event arguments of the event, take the property System.Windows.Forms.KeyEventArgs.Modifiers; it already has information of the state of the Shift key, see http://msdn.microsoft.com/en-us/library/system.windows.forms.keyeventargs.aspx[^].

Install MDSN help for your Visual Studio, you have a strong need for it. :-)

—SA
 
Share this answer
 
I see two possibilities here:

1. In the OnKeyDown event, you can use a KeyEventArgs parameter. It holds a boolean value telling whether Shift is pressed at the moment of event generation or not.

2. When validating a string that results from keypresses, don't focus on the keys pressed but on the characters resulting thereof. E.g. you can allow numbers and forbid everything else.
 
Share this answer
 
Several workable methods are documented here[^], and I'm sure one of them will work for you. In fact, I've wondered how to do this a few times myself. Thanks for a good question!
 
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