文字列 1行の高さの取得(WinAPI関数)

Windows で文字列の高さにを取得する方法はいくつかあります。
今回はそのうちの GetTextExtentPoint32 と GetTextMetrics です。

BOOL GetTextExtentPoint32 (HDC hdc,  LPCTSTR str, int len, LPSIZE psize);
BOOL GetTextMetrics (HDC hdc, LPTEXTMETRIC p_tm);
どちらも戻り値は、成功なら非0、失敗なら0です。


文字列 1行の高さの取得(WinAPI関数)

#include <stdio.h>
#include <windows.h>

// 1行の高さ  (GetTextExtentPoint32 版)
get_font_height_tep (HDC hdc, HFONT hfont=NULL){
    SIZE size;
    if (hfont) SelectObject(hdc, hfont);
    if (GetTextExtentPoint32(hdc, "M", 1, &size)) return size.cy;
    return 0;
}
// 1行の高さ  (GetTextMetrics 版)
get_font_height_tm (HDC hdc, HFONT hfont=NULL){
    if (hfont) SelectObject(hdc, hfont);
    TEXTMETRIC tm;
    if (GetTextMetrics(hdc, &tm)) return tm.tmHeight;
    return 0;
}
//============HWND 版=======================
// 1行の高さ  (HWND の GetTextExtentPoint32版)
get_font_height_tep(HWND hwnd, HFONT hfont){
    HDC hdc = GetDC(hwnd);
    int h = get_font_height_tep(hdc, hfont);
    ReleaseDC(hwnd, hdc);
    return h;
}
// 1行の高さ  (HWND の GetTextMetrics版)
get_font_height_tm(HWND hwnd, HFONT hfont){
    HDC hdc = GetDC(hwnd);
    int h = get_font_height_tm(hdc, hfont);
    ReleaseDC(hwnd, hdc);
    return h;
}

main(){
    int m, n;
    char s[20];

    m=get_font_height_tep(GetDesktopWindow(), NULL);
    n=get_font_height_tm(GetDesktopWindow(),NULL);
    printf("GetTextExtentPoint32 : %d\n", m);
    printf("GetTextMetrics : %d\n", n);

}







戻る