0

I am currently getting stuck with controlling components focus in C#.net. My goal is that preventing losing focus of Textbox A when "click" to another component (eg Textbox B or something). This "focus" mechanism will be kept except Textbox C or D ... is clicked.

enter image description here

That might sound so weird but my situation is that Each of those rows A,C,D is a datarepeater item, and I only want to vertically move "focus" on the right column, not B column.

So, It is possible to do that in C# or I've got to find another control (not Data repeater). Any helps would be grateful.

Junaith
  • 3,298
  • 24
  • 34
Kingcesc
  • 84
  • 1
  • 6
  • I have edited your title... see [Should questions include "tags" in their title](http://meta.stackoverflow.com/questions/19190/should-questions-include-tags-in-their-titles), where the consensus is "no, they should not – Junaith Jan 14 '15 at 08:14
  • 1
    What about attaching to the LostFocus event of your TextBox A, then check which Control currently has the focus and if it is TextBox B or any other 'not allowed' control simply call TextBoxA.Focus() again? – Tobias Breuer Jan 14 '15 at 08:18
  • @Tobias that might cost expensive cause I have to iterate all of the control to find out which is currently being focused. – Kingcesc Jan 14 '15 at 08:33
  • `var focusedControl = manyControls.FirstOrDefault(x => x.Focused)` will take less time than you can notice, for any number of controls lower than thousands, maybe even hundreds of thousands. I doubt you have this many controls. – SimpleVar Jan 14 '15 at 08:50

1 Answers1

0

You can use the Leave event of the TextBoxA along with a list that contains the controls that are allowed to acquire focus.

    [DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.Winapi)]
    internal static extern IntPtr GetFocus();

    private Control GetFocusedControl()
    {
        Control focusedControl = null;
        // To get hold of the focused control:
        IntPtr focusedHandle = GetFocus();
        if (focusedHandle != IntPtr.Zero)
            // Note that if the focused Control is not a .Net control, then this will return null.
            focusedControl = Control.FromHandle(focusedHandle);
        return focusedControl;
    }

    private void textBox3_Leave(object sender, EventArgs e)
    {
        //Any control that is allowed to acquire focus is just added to this array.
        Control[] allowedToAcquireFocusControls = { 
                 textBox1
            };

        Control focusedControl = GetFocusedControl();

        if (!allowedToAcquireFocusControls.Contains(focusedControl))
        {
            textBox3.Focus();
        }
    }

Reference: What is the preferred way to find focused control in WinForms app?

Community
  • 1
  • 1
Oday Fraiwan
  • 1,147
  • 1
  • 9
  • 21