C++Builder如何判断哪个组件有程序焦点

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

我正在使用 C++Builder XE4 32 位 VCL 平台。我正在为 Windows OS.

写作

我有一个 MainForm,上面有很多组件。当我按下键盘上的方向键并触发窗体的OnShortCut事件时,如何判断哪个组件获得了程序焦点?

根据焦点所在的组件,我必须采取不同的操作。

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

使用全局 Screen->ActiveControl 属性:

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...
}

或者,您可以使用表单自带的 ActiveControl 属性:

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...
}