Search code examples
c++buildervclc++builder-xe4

How to determine which component has the program focus in C++Builder


I am using C++Builder XE4 32bit VCL platform. I am writing for Windows OS.

I have a MainForm with a lot of components on it. When I press a keyboard arrow key and the Form's OnShortCut event is triggered, how do I determine which component has the program focus?

I have different actions which must be taken based on which component has the focus.

void __fastcall TMainForm::FormShortCut(TWMKey &Msg, bool &Handled)
{
    //determine which component has the focus.
}

Solution

  • Use the global Screen->ActiveControl property:

    Indicates which control currently has input focus on the screen.

    Read ActiveControl to learn which windowed control object in the active form currently receives the input from the keyboard.

    void __fastcall TMainForm::FormShortCut(TWMKey &Msg, bool &Handled)
    {
        TWinControl *ctrl = Screen->ActiveControl;
        if (ctrl == Control1)
        {
            // do something...
        }
        else if (ctrl == Control2)
        {
            // do something else...
        }
        // and so on...
    }
    

    Or, you can use the Form's own ActiveControl property:

    Specifies the control that has focus on the form.

    Use ActiveControl to get or set the control that has focus on the form. Only one control can have focus at a given time in an application.

    If the form does not have focus, ActiveControl is the control on the form that will receive focus when the form receives focus.

    void __fastcall TMainForm::FormShortCut(TWMKey &Msg, bool &Handled)
    {
        TWinControl *ctrl = this->ActiveControl;
        if (ctrl == Control1)
        {
            // do something...
        }
        else if (ctrl == Control2)
        {
            // do something else...
        }
        // and so on...
    }