Click here to Skip to main content
15,891,529 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
hi i have about 50 textboxes on a single windows form. i dont want to write keypress event for each textbox. is there any parent form level event which detect that there is keypress on any of the textbox.
i have tried so far:
C#
[DllImport("user32.dll"]
internal static extern IntPtr GetFocus();
private Control GetFocusedControl()
        {
            Control focusedControl = null;
            IntPtr focusedHandle = GetFocus();
            if (focusedHandle != IntPtr.Zero)               
            focusedControl = Control.FromHandle(focusedHandle);
            return focusedControl;
        }
private void Form1_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (GetFocusedControl().GetType().ToString() == "System.Windows.Forms.TextBox")
           
            {
               //my code...
            }
                     
           
        }

but when the active control is a textbox form1_keypress event not being fired??
any help will be highly appreciated....
Posted

set
C#
this.KeyPreview = true;

and use this code
C#
private void Form1_KeyPress(object sender, KeyPressEventArgs e)
       {
           foreach (Control con in this.Controls)
           {
               if (con is TextBox)
               {
                   if (con.Focused)
                   {
                       //Do somthing for Focused text box
                       con.Text = "s";
                   }
               }
           }
       }

or use this code:
C#
private void Form1_KeyPress(object sender, KeyPressEventArgs e)
{
    Control con = this.ActiveControl;
    if (con is TextBox)
    {
            //Do somthing for Focused text box or Write event
            con.Text = "s";
    }
}
 
Share this answer
 
v3
C#
public Form1()
{
    InitializeComponent();
    CreateKeyPressEvent(this.Controls);
}

void CreateKeyPressEvent(System.Windows.Forms.Control.ControlCollection ctrls)
{
    foreach (Control c in ctrls)
    {
        if (c is TextBox)
        {
            c.KeyPress += new KeyPressEventHandler(c_KeyPress);
        }
        else
            CreateKeyPressEvent(c.Controls);
    }
}

void c_KeyPress(object sender, KeyPressEventArgs e)
{
    TextBox tb = (TextBox)sender;
    // Do whatever you want with this "tb"
}
 
Share this answer
 
Comments
choudhary.sumit 18-Oct-12 4:52am    
thanks dear.
it works great!! :)
Form.KeyPreview Property[^]

Just set
C#
this.KeyPreview = true;
in the constructor & you will able to receive all KeyPress, KeyDown, and KeyUp events
 
Share this answer
 
v2

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