Finding a string's pixel width

This is a discussion on Finding a string's pixel width within the Windows Programming forums, part of the Platform Specific Boards category; I'm sure this problem has a simple solution: How do I find the pixel width of a given displayed string ...

  1. #1
    Registered Abuser
    Join Date
    Jun 2006
    Location
    Toronto
    Posts
    591

    Finding a string's pixel width

    I'm sure this problem has a simple solution: How do I find the pixel width of a given displayed string using a given font on a given device?
    I know there must be some simple solution as some Window controls even have built in functions to do exactly this (i.e. ListViews have ListView_GetStringWidth, which is close to what I need, but instead I need one for use with a ComboBoxEx).
    So far I've tried this:
    Code:
    LOGFONT lf;
    //Get Current Font
    lf.lfWidth;
    stringPixelWidth = strlen(string)*lf.lfWidth;
    However two problems arise: 1) lfWidth is only the *average* width of a character and 2) the lfWidth can be zero. I thought of using lfHeight instead but then realized that unlike string widths, string heights are mostly constant).

    So is there a function or macro that I can use to find out the pixel width of a given string?
    (in particular: this is for use with setting the width of the dropdown listbox of combo box)

  2. #2
    Yes, my avatar is stolen anonytmouse's Avatar
    Join Date
    Dec 2002
    Posts
    2,544
    GetTextExtentPoint32 (via MSDN: Font and Text Functions).

  3. #3
    Registered Abuser
    Join Date
    Jun 2006
    Location
    Toronto
    Posts
    591
    anonytmouse saves the day again, thanks! <bookmarked>

    p.s. I notice the link is to the new MSDN site, (bad habit has made me stick with the old one still) do they contain the same documentation or should I switch to the new one in order to find functions like these?
    Last edited by @nthony; 08-03-2006 at 02:19 AM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Finding similar words from 2 strings
    By lzhaol in forum C++ Programming
    Replies: 7
    Last Post: 02-26-2006, 12:45 AM
  2. Problems with strings as key in STL maps
    By all_names_taken in forum C++ Programming
    Replies: 3
    Last Post: 01-17-2006, 10:34 AM
  3. Reading strings input by the user...
    By Cmuppet in forum C Programming
    Replies: 13
    Last Post: 07-21-2004, 06:37 AM
  4. libtiff: TIFFWriteRGBAImage()?
    By dug in forum Game Programming
    Replies: 1
    Last Post: 07-09-2003, 09:01 AM
  5. c-style string vs. c++-style strings
    By Mbrio in forum C++ Programming
    Replies: 3
    Last Post: 02-10-2002, 11:26 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21