Click here to Skip to main content
15,911,360 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
hello
I want to set focus to form.
means in my application some label, text box and check box when i run this application then focus are in text box.but i want focus in form so i can set focus to form if yes then tell me the way for that. because i want to use form's key down event when i start my application
Posted
Updated 31-Jan-12 23:07pm
v2

You can't set the focus to the form in the way you want - it doesn't have any user editable parts - the focus goes to the textbox because it is the first control in the Tab Order which can accept user input.

If you want to handle the KeyDown event for all the controls in your form, as well as teh form itself, then you have to add the handler to each, either in the designer, or in the form Load event:
C#
private void myForm_Load(object sender, EventArgs e)
    {
    foreach (Control c in Controls)
        {
        c.KeyDown += new KeyEventHandler(myForm_KeyDown);
        }
    }

void myForm_KeyDown(object sender, KeyEventArgs e)
    {
    ...
    }
 
Share this answer
 
Comments
Dharmessh12 1-Feb-12 5:40am    
thanks but i got my anser....
if we set key Preview property of form then we can use key down event of form...by default it:s false .for that we have to do true..
Michel [mjbohn] 1-Feb-12 10:47am    
So if you got it from my solution, it would be nice to formally accept it. :)
You can set the KeyPreview property of your form to True

From MSDN:
When this property is set to true, the form will receive all KeyPress, KeyDown, and KeyUp events. After the form's event handlers have completed processing the keystroke, the keystroke is then assigned to the control with focus. For example, if the KeyPreview property is set to true and the currently selected control is a TextBox, after the keystroke is handled by the event handlers of the form the TextBox control will receive the key that was pressed. To handle keyboard events only at the form level and not allow controls to receive keyboard events, set the KeyPressEventArgs..::.Handled property in your form's KeyPress event handler to true.


example:
C#
protected override void OnKeyDown( KeyEventArgs e )
{
    // check for Ctrl.X
    if (e.KeyCode == Keys.X && Control.ModifierKeys == Keys.Control)
    {
        // your code to handle Ctrl.X
        
        e.Handled = true; // Decide whether or not focused control shall receive keystroke.
    }
}



regards
Michel
 
Share this answer
 
Try this may help you
this.Focus();


Thanks
--RA
 
Share this answer
 
Comments
Dharmessh12 1-Feb-12 5:14am    
thanks but i have try but it;s nit solved my problem

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