Marcelo Camargo
Marcelo Camargo

Reputation: 2298

Get the focused component in Windows Forms

I need to get the component that has the focus in the moment with Windows Forms and .NET Framework 2.0 - C# or VisualBasic

I have an event that, in some moment, receive a text and it needs to put this text inside of a TextBox component. But it isn't just a component. Must be the focused component. My situation is: I'm working with low level applications and hardware communication that gets a string from a hardware reader and I must append this text to the focused TextBox.

_device = new Device(Device.AvailableDevices[0].DeviceName);
_leitor = new Reader(_device);
_leitorDados = new ReaderData(ReaderDataTypes.Text, ReaderDataLengths.MaximumLabel);
_leitor.Actions.Enable();
_leitor.Actions.Read(_leitorDados);
_leitor.StatusNotify += delegate
{
    if (_leitorDados.Text == String.Empty) return;
    MessageBox.Show(_leitorDados.Text);
    _leitorDados = new ReaderData(ReaderDataTypes.Text, ReaderDataLengths.MaximumLabel);
    _leitor.Actions.Read(_leitorDados);
}; 

My text is found in _leitorDados.Text and, when I receive the event, I need to do

focusedControl.Text = _leitorDados.Text;

But I'm using a very limited version of .NET Framework, the 2.0 and I have not so many possibilities to do it. Thanks in advance.

enter image description here

Upvotes: 0

Views: 790

Answers (1)

nevets
nevets

Reputation: 4828

You should do this using a recursive approach. Try this:

public static Control FindFocusedComponent(Control control)
{
    foreach (Control child in control.Controls)
    {
        if (child.Focused)
        {
            return child;
        }
    }

    foreach (Control child in control.Controls)
    {
        Control focused = FindFocusedComponent(child);

        if (focused != null)
        {
            return focused;
        }
    }

    return null;
}

Upvotes: 1

Related Questions