IWebBrowser2模拟左键单击

时间:2014-06-06 17:10:08

标签: c++ click sendmessage postmessage iwebbrowser2

我要实现的是模拟使用IWebBrowser2类创建的Web浏览器中的左键单击。

当前代码

if (SUCCEEDED(OleInitialize(NULL))){
    IWebBrowser2*    pBrowser2;

    CoCreateInstance(CLSID_InternetExplorer, NULL, CLSCTX_LOCAL_SERVER, 
                   IID_IWebBrowser2, (void**)&pBrowser2);
    if (pBrowser2){
        VARIANT vEmpty;
        VariantInit(&vEmpty);

        BSTR bstrURL = SysAllocString(L"http://google.pl");

        HRESULT hr = pBrowser2->Navigate(bstrURL, &vEmpty, &vEmpty, &vEmpty, &vEmpty);
        if (SUCCEEDED(hr))
        {
            pBrowser2->put_Visible( VARIANT_FALSE );
            pBrowser2->put_FullScreen( VARIANT_TRUE );
        }
        else
        {
            pBrowser2->Quit();
        }

        srand( time( NULL ) );

        Sleep( ( std::rand() % 5000 ) + 5000 );

        if(std::rand() % 100 > chance ){
            SysFreeString(bstrURL);             
            pBrowser2 -> Release();

            return;
        }

        HWND handle;

        if( pBrowser2 -> get_HWND( ( long *)&handle ) !=  S_OK ){
            return;
        }

        IServiceProvider* pServiceProvider = NULL;

        if (SUCCEEDED(pBrowser2->QueryInterface(IID_IServiceProvider, (void**)&pServiceProvider))){
            IOleWindow* pWindow = NULL;

            if (SUCCEEDED(pServiceProvider->QueryService(
                SID_SShellBrowser, 
                IID_IOleWindow,
                (void**)&pWindow))){

                HWND hwndBrowser = NULL;

                if (SUCCEEDED(pWindow->GetWindow(&hwndBrowser))){
                    RECT windowRect;

                    GetWindowRect( hwndBrowser , &windowRect );

                    for( int i = 0 ; i < 100 ; i++ ){
                        //just for test
                        int positionX = ( ( std::rand() ) % ( windowRect.right - windowRect.left ) ) + windowRect.left;
                        int positionY = ( ( std::rand() ) % ( windowRect.bottom - windowRect.top ) ) + windowRect.top;

                        printf( "%d | %d\n",positionX,positionY);

                        PostMessage( hwndBrowser, WM_LBUTTONDOWN, 0, MAKELPARAM(positionX,positionY) );
                        Sleep( 10 );
                        PostMessage ( hwndBrowser, WM_LBUTTONUP, 0, MAKELPARAM(positionX,positionY) );
                    }
                }

                pWindow->Release();
            }

        pServiceProvider->Release();

        } 

        pBrowser2->put_Visible(VARIANT_TRUE);

        SysFreeString(bstrURL);             
        pBrowser2 -> Release();

    }

    OleUninitialize();
}

但没有任何事情发生。此外,我尝试使用SendMessage并显示/不显示窗口。

第二种方法是访问dom并尝试调用click事件,但这可能吗?

0 个答案:

没有答案