如何检测焦点窗口是否为编辑类型'控制?

时间:2016-04-27 06:03:13

标签: c++ winapi

如何检测焦点窗口是否为编辑类型'控制?我所知道的一种方法是使用Microsoft Active Accessibility,看起来它会使用这种方法付出很多努力。

我可以使用的另一种方法更简单吗?

我的用例是:当编辑控件具有焦点时,存储hwnd

// Callback set by SetWinEventHook(EVENT_OBJECT_FOCUS, EVENT_OBJECT_FOCUS, NULL, (WINEVENTPROC)&winEventProc, 0, 0, WINEVENT_SKIPOWNPROCESS);
void CALLBACK KeyboardComponent::winEventProc(HWINEVENTHOOK hWinEventHook, DWORD  event, HWND hwnd, LONG idObject,
    LONG idChild, DWORD dwEventThread, DWORD dwmsEventTime)
{
    // if hwnd == "Edit Control" store hwnd to send key input events

    // One technique but not comprehensive
    TCHAR wndClassName[255];
    GetClassName(hwnd, wndClassName, 255);

    if (_tcsicmp(wndClassName, _T("edit")) == 0)
        targetEdit = hwnd;

    // Class names I am receiving are subclassed or new window classes that look and operate like Edit controls.
    // Ie when clicking the Firefox address bar I get: MozillaWindowClass
    // Ie when clicking the Chrome address bar I get:  Chrome_WidgetWin_1
}

3 个答案:

答案 0 :(得分:1)

Active Accessibility是正确的解决方案。您可以使用AccessibleObjectFromEvent()为触发HWND挂钩的winEventProc获取IAccessible界面,然后检查ROLE_SYSTEM_TEXT属性{{1} }:

  

ROLE_SYSTEM_TEXT
  该对象表示允许编辑的可选文本或指定为只读。

例如:

// Callback set by SetWinEventHook(EVENT_OBJECT_FOCUS, EVENT_OBJECT_FOCUS, NULL, (WINEVENTPROC)&winEventProc, 0, 0, WINEVENT_SKIPOWNPROCESS);
void CALLBACK KeyboardComponent::winEventProc(HWINEVENTHOOK hWinEventHook, DWORD  event, HWND hwnd, LONG idObject,
    LONG idChild, DWORD dwEventThread, DWORD dwmsEventTime)
{
    IAccessible* pAcc = NULL;
    VARIANT varChild;
    HRESULT hr = AccessibleObjectFromEvent(hwnd, idObject, idChild, &pAcc, &varChild);  
    if ((hr == S_OK) && (pAcc != NULL))
    {
        VARIANT varRole;
        hr = pAcc->get_accRole(varChild, &varRole);
        if ((hr == S_OK) && (varRole.vt == VT_I4) && (varRole.lVal == ROLE_SYSTEM_TEXT))
        {
            // ... 
        }
        pAcc->Release();
    }
}

答案 1 :(得分:-1)

为了获得可靠的结果,尝试使用RealGetWindowClass,它应该处理窗口被子类化的情况。如果您不关心,请使用常规GetClassName

如果你想处理不是从标准Edit类派生的控件,当然这些都不会起作用。

答案 2 :(得分:-2)

您可以使用此代码来了解焦点窗口是否为编辑控件

CWnd* pControl; 
pControl = this->GetFocus();

if(pControl->IsKindOf(RUNTIME_CLASS(CEdit))){
      //----
       -----
       ----//
}

获取更多详情Here

Cwnd转换为HWND

pControl->GetSafeHwnd();