Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

Convert WinApi type to Qt type



  • Hi
    This code is working fine, but in ending I got error (debug) "Exception at 0x5313a407, code: 0xc0000005: read access violation at: 0x0, flags=0x0"
    @ HWND activeWindow;
    activeWindow = GetForegroundWindow();
    LPWSTR l_windowTitle;
    SetWindowText(activeWindow,L"Hi!");
    GetWindowText(activeWindow,l_windowTitle,256);
    QString wchr = QString::fromWCharArray(l_windowTitle);
    qDebug()<<wchr;@
    Why?



  • Edit code
    @ HWND activeWindow;
    activeWindow = GetForegroundWindow();
    LPWSTR l_windowTitle = L"";
    LPWSTR l_windowTitle2;
    GetWindowText(activeWindow,l_windowTitle,256);
    GetWindowText(activeWindow,l_windowTitle2,256);

    qDebug()<<QString::fromWCharArray(l_windowTitle);
    qDebug()<<QString::fromWCharArray(l_windowTitle2);@
    

    output without error
    ""
    ""


    @ HWND activeWindow;
    activeWindow = GetForegroundWindow();
    LPWSTR l_windowTitle;
    GetWindowText(activeWindow,l_windowTitle,256);

    qDebug()<<QString::fromWCharArray(l_windowTitle);
    

    @

    output with error
    "Title message"



  • And now I am editing my code and this work perfectly. But why? ^_^

    @ HWND activeWindow;
    activeWindow = GetForegroundWindow();
    char testVar[256];
    GetWindowTextA(activeWindow,testVar,sizeof testVar);

    qDebug()<<testVar;@


  • How should it work if you didn't initialized your wchar_t variables?
    LPWSTR is simple pointer in memory of wchar_t type:
    @
    // LPWSTR l_windowTitle is the same as
    wchar_t * windowTitle;
    @

    And after what you are trying to get 256 bytes to this uninitialized place in memory, of cause it will fail!

    @
    //
    HWND activeWindow = GetForegroundWindow();
    LPWSTR l_windowTitle = new wchar_t[256]; // or better use winapi memory initialization functions if you use wrappers for wchar_t type
    GetWindowText(activeWindow,l_windowTitle,255);// let 1 byte for \0
    qDebug()<<QString::fromWCharArray(l_windowTitle);
    // free memory after you don't need it anymore
    delete [] l_windowTitle;
    @



  • Thanks ^_^



  • Please add "[SOLVED]" prefix left to the subject topic. And have fun with coding!


Log in to reply