CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 5 of 5

Threaded View

  1. #4
    2kaud's Avatar
    2kaud is offline Super Moderator Power Poster
    Join Date
    Dec 2012
    Location
    England
    Posts
    7,923

    Re: Problem with text in GetWindowText function

    Code:
    HWND TextBox, Button;
    A problem is here. These are initialised in WM_CREATE, but when WndProc() exits, these values are 'lost'. So when Wndproc() is entered again, these variables have unknown values (NOT the previously assigned values) - but are unlikely to be valid window handles. GetWindowText() is likely to fail (returns 0). As you aren't testing that the functions used have completed properly, you aren't handling errors. When you use a function that can fail, you always need to check for such failure. The MSDN documentation describes this. Likewise, the textSaved array isn't initialised either, so if GetWindowText() fails, then MessageBox() will display whatever happens to be at the memory locations used by textSaved - probably the garbage you are seeing displayed.

    In this case, any 'easy' solution is make TextBox and Button static so that their values remain between successive calls to WndProc().

    Code:
    static HWND TextBox = 0, Button = 0;
    A better way of coding of case 1 could be:

    Code:
    TCHAR textSaved[20] = {0};
    int gwtstat = GetWindowTextLength(TextBox);
    
    if (gwstat > 0)
        if ((gwstat = GetWindowText(TextBox, textSaved, gwtstat)) > 0)
            ::MessageBox(hwnd, textSaved, "Title", MB_OK);
    
    if (gwstat == 0)
        ::MessageBox(hwnd, "Problem obtaining window text", "Title", MB_OK);
    
    break;
    Using TCHAR rather than char should enable this to work with either UNICODE or MBCS coding.
    Last edited by 2kaud; April 27th, 2020 at 04:10 AM.
    All advice is offered in good faith only. All my code is tested (unless stated explicitly otherwise) with the latest version of Microsoft Visual Studio (using the supported features of the latest standard) and is offered as examples only - not as production quality. I cannot offer advice regarding any other c/c++ compiler/IDE or incompatibilities with VS. You are ultimately responsible for the effects of your programs and the integrity of the machines they run on. Anything I post, code snippets, advice, etc is licensed as Public Domain https://creativecommons.org/publicdomain/zero/1.0/ and can be used without reference or acknowledgement. Also note that I only provide advice and guidance via the forums - and not via private messages!

    C++23 Compiler: Microsoft VS2022 (17.6.5)

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured