c++ - 使用通配符与 FindWindow api 调用与 mfc

标签 c++ api mfc findwindow

我在 mfc 应用程序中使用 FindWindow。

HWND hWnd = ::FindWindow(NULL, _T("foobar v5"));

我想将 FindWindow 与通配符一起使用,这样我就可以只匹配 foobar。

谢谢

最佳答案

您必须创建自己的实现,该实现应基于 EnumWindows、GetWindowText 和 GetWindowTextLength,然后必须允许通配符。

#include <Windows.h>
#include <iostream>
#include <string>
#include <vector>

struct FindWindowData {
    FindWindowData( TCHAR const * windowTitle )
        : WindowTitle( windowTitle )
        , ResultHandle( 0 )
    {}

    std::basic_string<TCHAR> WindowTitle;
    HWND ResultHandle;
};

BOOL CALLBACK FindWindowImpl( HWND hWnd, LPARAM lParam ) {
    FindWindowData * p = reinterpret_cast<FindWindowData*>( LongToPtr( lParam ) );
    if( !p ) {
        // Finish enumerating we received an invalid parameter
        return FALSE;
    }

    int length = GetWindowTextLength( hWnd ) + 1;
    if( length > 0 ) {
        std::vector<TCHAR> buffer( std::size_t( length ), 0 );      
        if( GetWindowText( hWnd, &buffer[0], length ) ) {
                    // Comparing the string - If you want to add some features you can do it here
            if( _tcsnicmp( &buffer[0], p->WindowTitle.c_str(), min( buffer.size(), p->WindowTitle.size() )  ) == 0 ) {
                p->ResultHandle = hWnd;
                // Finish enumerating we found what we need
                return FALSE;
            }
        }
    }
    // Continue enumerating
    return TRUE;
}

// Returns the window handle when found if it returns 0 GetLastError() will return more information
HWND FindWindowStart( TCHAR const * windowTitle ) {

    if( !windowTitle ) {
        SetLastError( ERROR_INVALID_PARAMETER );
        return 0;
    }

    FindWindowData data( windowTitle );
    if( !EnumWindows( FindWindowImpl, PtrToLong(&data) ) && data.ResultHandle != 0 ) {
        SetLastError( ERROR_SUCCESS );
        return data.ResultHandle;
    }

    // Return ERROR_FILE_NOT_FOUND in GetLastError
    SetLastError( ERROR_FILE_NOT_FOUND );
    return 0;
}

int _tmain(int argc, _TCHAR* argv[])
{
    std::cout << "HWND: " << FindWindowStart(TEXT("foobar ") );
    std::cout << "  GetLastError() = " << GetLastError() << std::endl;
    return 0;
}

关于c++ - 使用通配符与 FindWindow api 调用与 mfc,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3922488/

相关文章:

multithreading - 工作线程没有消息循环(MFC,Windows)。我们可以使其接收消息吗?

c++ - 在 MFC 中,当 CEdit 控件达到最大字符数时,退格键不起作用

c++ - CDialog ShowWindow问题

c++ - 循环和if的优化

c++ - 在 C++ 中使用 "+"连接字符串

python - 向 reddit api 添加对 flair 的支持

javascript - API 调用未返回数据。 http.get()

windows - 创建独立于操作系统的 GUI 软件的可能性

C++ 在 if/else if 中启动不同的文件

c++ - 如果在 Xeon Phi 上编译时不知道循环计数,则性能会下降