Thread: GetWindowTextW

  1. #1
    Registered User mrafcho001's Avatar
    Join Date
    Jan 2005
    Posts
    483

    GetWindowTextW

    I seem to be misunderstanding the GetWindowText function. I though you are supposed to pass a buffer where the function can write the title, so that means that the buffer has to be (in UNICODE):

    (size of the title) * 2 + 2

    multiply by 2 because each UNICODE character is 2 bytes wide, and + 2 for the zero terminating sign.

    Am I right so far?

    But how in the world does this work?

    Code:
    LPWSTR lp = (LPWSTR)GlobalAlloc(GPTR, 1);
    GetWindowText(hwnd, lp, GetWindowTextLength(hwnd)+1);
    MessageBox(NULL, lp, lp, 0);
    Also after im done using the pointer to the title do I just call GlobalFree() to free the space?
    My Website
    010000110010101100101011
    Add Color To Your Code!

  2. #2
    Registered User
    Join Date
    Jan 2005
    Posts
    847
    It works because of memory allignment. A bigger chunk of memory can be allocated then what you requested. It would be very bad to depend on this though.

  3. #3
    Registered User mrafcho001's Avatar
    Join Date
    Jan 2005
    Posts
    483
    I don't think i quite understand what you said.
    My Website
    010000110010101100101011
    Add Color To Your Code!

  4. #4
    erstwhile
    Join Date
    Jan 2002
    Posts
    2,227
    Just because you request 1 byte to be allocated doesn't mean only one byte will be - you might get a bigger chunk, still "guaranteed to be aligned on an 8-byte boundary" (see GlobalAlloc) but, as Quantum1024 has already pointed out, you shouldn't rely on this. You can always try using the GlobalSize function to determine the size of memory returned.
    Last edited by Ken Fitlike; 05-13-2006 at 10:06 PM.
    CProgramming FAQ
    Caution: this person may be a carrier of the misinformation virus.

  5. #5
    Registered User mrafcho001's Avatar
    Join Date
    Jan 2005
    Posts
    483
    Thanks guys, I finaly understand this.

    So when the function asks for a pointer to a buffer the pointer is really pointing to the begining of the buffer, and the function assumes that there is enough space allocated, but if there isn't it just keeps writting into the memory following the one you have already alocated.

    I though windows had some kind of mechanism to check for this kind of stuff, but I guess not.
    My Website
    010000110010101100101011
    Add Color To Your Code!

Popular pages Recent additions subscribe to a feed