Click here to Skip to main content
15,892,927 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi every one,

i am new to windows application.when i press (contrail+left) arrow button.button click event has to fire.if no controls are there in form it is working fine.but if any controls are there in form it is not working.because focus is going on to that control.please help me any one here is my code..


C#
private void Short_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
       {
           if (Control.ModifierKeys == Keys.Control && e.KeyCode == Keys.Left)
           {
               MessageBox.Show("left");
               // button1.Focus();

           }
           else if (Control.ModifierKeys == Keys.Control && e.KeyCode == Keys.Right)
           {
               MessageBox.Show("right");
            
           }

       }
Posted
Updated 24-Feb-14 5:39am
v3

Probably you forgot one more detail: to set the property KeyPreview to true for your form. Use with care: it is set to false by default, on purpose. Please see:
http://msdn.microsoft.com/en-us/library/system.windows.forms.form.keypreview%28v=vs.110%29.aspx[^].

—SA
 
Share this answer
 
Comments
Maciej Los 24-Feb-14 12:17pm    
+5
Sergey Alexandrovich Kryukov 24-Feb-14 12:19pm    
Thank you, Maciej.
—SA
CHill60 24-Feb-14 13:20pm    
+5
Sergey Alexandrovich Kryukov 24-Feb-14 13:27pm    
Thank you.
—SA
Bitto kumar 24-Feb-14 22:42pm    
thank you so much for your help.it's working fine now.
Your problem here, as I think you've already become aware, is that with Controls on the Form, the Form is never going to have 'Focus, so: the PreViewKeyDown EventHandler is never going to fire.

Use the KeyDown Event instead:
C#
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
    if (Control.ModifierKeys == Keys.Control)
    {
        switch (e.KeyCode)
        {
            case Keys.Left:
                Console.WriteLine("control-left");
                button1.PerformClick();
                break;
            case Keys.Right:
                Console.WriteLine("control-right");
                break;
        }
    }
}
I suggest you use Console.WriteLine while debugging rather than using 'MessageBox.Show: it's less "intrusive."

Finally, I'd like to note that simulating a Button Click using a key-combination like this is a very unusual design choice, and one that may confuse users. It would be better, imho, to have a common method that would be called by both the Button being clicked, and by the key-combination.
 
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