Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Help setting focus on the parent

I have a simple situation (.NET2): a texbox1 on a UserControl1(or Form1).

I want to unfocus(leave) the texbox when I click on the usercontrol/form(focus the usercontrol/form instead): alt text http://lh3.ggpht.com/_1TPOP7DzY1E/S0R1ORVt-pI/AAAAAAAAC3Y/UkS2zEMWa9o/s800/Capture4.png

I do the following on the UC/form:

      Protected Overrides Sub OnMouseClick _
          (ByVal e As System.Windows.Forms.MouseEventArgs)
        MyBase.OnMouseClick(e)
        Me.Focus()
      End Sub

Why does it not work on the child textbox, but works very well on the non-child one(focus on textBox2 then click on the panel removes the focus from the textBox2)?

Real project Window

alt text http://lh5.ggpht.com/_1TPOP7DzY1E/S0SVniaeN1I/AAAAAAAAC3g/jafhFG-vA0g/s800/Capture5.png

like image 491
serhio Avatar asked Apr 26 '26 08:04

serhio


1 Answers

  1. Add a new panel control to your form (somewhere out of the way) and resize it to 0,0
  2. Do NOT set Visible = false on this panel.
  3. In your form add a standard MouseClick event handler as follows:

    private void Form1_MouseClick(object sender, MouseEventArgs e)
    {
        // Uncomment if in scrollable control
        //Point scrollPos = new Point(this.AutoScrollPosition.X, -this.AutoScrollPosition.Y);
        newPanel.Select(); 
        // Uncomment if in scrollable control
        //this.AutoScrollPosition = scrollPos;
    
    }
    
  4. Now, when you click anywhere on your main form, any input control will lose focus and you will be able to handle the usual Validating events etc.
like image 96
Ash Avatar answered Apr 28 '26 10:04

Ash



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!