"Windows Programming" series Third: Text character output

Source: Internet
Author: User
Tags drawtext textout

In the previous article we showed how to create a basic control using the Windows SDK, this article discusses how to output text characters.

When programming with WIN32, we often want to output text to the window, all of the text characters or graphics output from Windows is done through the Graphics Device Interface (GDI), and the GDI32.dll of one of the three core components of Windows encapsulates all text and image output.

    • Basic knowledge of GDI

Windows wants to draw and output text, all through GDI (graphics device Interface, graphic Devices Interface), GDI is the device context in which Windows paints graphics, including brushes, brushes, fonts, bitmaps, and many other drawing-related objects. The device Environment (DC) plays a crucial role in drawing. Almost all of the drawing (including graphics and text) is related to the device environment, noting the meaning of "environment", as we paint and write on the canvas, which is the drawing canvas, what pen, what color, what brush is used to fill the canvas, and so on, which is the environment of our drawing, The same is true of the DC device context for Windows drawings. The device environment handle (HDC) is the handle that describes the DC, so as long as you have the handle, you have the condition to output graphics and text on the window. You get the HDC of the window client area, you can draw on the window client area, you get the window's non-client area hdc, you can draw on it, you get the desktop hdc, you can draw directly on the desktop ...

There are two ways to get the device environment handle: one is to process the WM_PAINT message and return through the BeginPaint function. Another is obtained through the API functions of GetDC and GETWINDOWDC.

    • Get DC via WM_PAINT message

Windows proactively requests processing of WM_PAINT messages when it detects the need to redraw or refresh the window. For example, in the following cases will be actively seeking processing:

    1. The user moves a window, causing the part of the window that was originally covered to appear.
    2. The user adjusts the size of the window, and the window style type is set to Cs_hredraw and Cs_vredraw.
    3. The program calls the ScrollWindow or SCROLLDC function to scroll the client area.
    4. The program calls the InvalidateRect or InvalidateRgn function, which displays the production of a WM_PAINT message.

We can finish drawing in this message, the processing of this message has a specific format, must be called before the actual drawing, call the EndPaint function after the completion of the BeginPaint, that is, we need to put all the drawing functions between the two functions, And HDC can only be used in between, and can not be stored in other places to use. One advantage of using WM_PAINT is that Windows calculates which areas need to be updated on its own, meaning that only the real changes will be updated, so the cost of updating will be minimized.

    • Get HDC through API functions

We can also get the HDC through the GETDC, GETWINDOWDC function, but note that the HDC obtained through this can be saved for use at other times, but remember that once the window is updated, it must be redrawn, or it will disappear. Finally, you need to call ReleaseDC after use to release, otherwise it will cause a resource leak.

    • Create a specific font

The most common text output is that we do not need to create fonts ourselves, because the common objects have a system pre-defined good. If you want to output a special (non-system predefined) font, we need to create and automatically select the device environment. There are CreateFont and createfontindirect to create the font, the parameters of both functions are many, basically the same, the specific usage look at the following example.

    • Implementing text rendering

With the above basis, we can through the Windows API to complete the text output, the common text output function has textout, DrawText, Drawtextext, ExtTextOut, and so on, these functions basically have similar parameters, such as HDC, The coordinate position, string. The following textout, DrawText, and ExtTextOut are examples of how to output text in a Windows window, and see the use of MSDN for additional information.

#include <windows.h> #include <tchar.h>static tchar szappname[] = TEXT ("Textout"); static LRESULT CALLBACK WndProc (HWND, UINT, WPARAM, LPARAM); int WINAPI WinMain (hinstance hinstance, hinstance hprevinstance, PSTR szcmdline, int     Icmdshow) {HWND hwnd;     MSG msg;     Wndclass Wndclass; Wndclass.style = Cs_hredraw |     Cs_vredraw;     Wndclass.lpfnwndproc = WndProc;     Wndclass.cbclsextra = 0;     Wndclass.cbwndextra = 0;     Wndclass.hinstance = hinstance;     Wndclass.hicon = LoadIcon (NULL, idi_application);     Wndclass.hcursor = LoadCursor (NULL, Idc_arrow);     Wndclass.hbrbackground = (hbrush) getstockobject (White_brush);     Wndclass.lpszmenuname = NULL;     Wndclass.lpszclassname = Szappname; if (! RegisterClass (&wndclass)) {MessageBox (NULL, TEXT ("This program requires Windows nt!"), Szappname, Mb_ic          ONERROR);     return 0; } hWnd = CreateWindow (szappname,//window class Name Szappname,//Window caption Ws_overlappedwindow,//Win       Dow style Cw_usedefault,//initial x position Cw_usedefault,                 Initial y position,//initial x size 300,                          Initial y size NULL,//parent window Handle                          NULL,//Window menu handle HINSTANCE,//program instance handle               NULL);     Creation Parameters ShowWindow (hWnd, icmdshow);          UpdateWindow (HWND);          while (GetMessage (&msg, NULL, 0, 0)) {translatemessage (&msg);     DispatchMessage (&AMP;MSG); } return Msg.wparam;} Static LRESULT CALLBACK WndProc (HWND hwnd, UINT message, WPARAM WPARAM, LPARAM LPARAM) {HDC Hdc;paIntstruct ps;switch (message) {case Wm_create:return 0;case wm_paint:{rect RECT = {10, 30, 100, 50}; TCHAR str[] = TEXT ("中文版 and Chinese"); HDC = BeginPaint (hWnd, &ps); TextOut (HDC, ten, ten, str, _tcslen (str)); SetTextColor (hdc, RGB (255,0,0));D Rawtext (hdc, STR,-1, &rect, dt_left| Dt_vcenter); SetTextColor (HDC, RGB (0,255,0)); INT dx[] = {8,8,8,8,16,8,8,8,16,8,8,8,10}; ExtTextOut (HDC, ten, 0, &rect, str, _tcslen (str), DX); SetTextColor (HDC, RGB (0,0,255)); rect.right = 110;rect.top = 70;rect.bottom = 82; ExtTextOut (HDC, ten, Rect.top, eto_clipped, &rect, str, _tcslen (str), DX); Hfont Hfont = CreateFont (///nheight, character height of the created font 0,//nwidth, font average width of characters,//Nescape ment, the character output direction is angled to the horizontal right direction, in 0.1 degrees 0,//norientation, the angle of the character and the baseline, in 0.1 degrees fw_bold,//nweight, the depth of the character color Light true,//Bitalic, Italic property flag (false: Normal font, true: Italic) FALSE,//bunderline, underscore attribute flag (false: No underscore, true: there Underline) FALSE,//cstrikeout, Strikethrough attribute flag (FALSE: No Strikethrough, TRUE: There is strikethrough) Ansi_charset,//Ncharset, Character set identity 0:ansi character set, 1: System default Character Set Out_default_precis,//Noutprecision , output accuracy Clip_default_precis,//nclipprecision, cut accuracy default_quality,//nquality, Output quality default_pitch|          Ff_swiss,//npitchandfamily, Character spacing text ("Arial")); Lpszfacename, existing system TrueType font name Hfont Holdfont = (hfont) SelectObject (HDC, Hfont); SetBkMode (HDC, TRANSPARENT); SetTextColor (HDC, RGB (0x00, 0xFF, 0xFF)); TextOut (HDC, 0, Max, TEXT ("Create Font"), 6);D eleteobject (Hfont); EndPaint (HWnd, &ps);} return 0;case wm_destroy:postquitmessage (0); return 0;} Return DefWindowProc (hWnd, message, WParam, LParam);}

program run, click the left mouse button after the effect is as follows:

Program in the DrawText, ExtTextOut can set the text output of the rectangular range, beyond the part is invisible, from the running results we can also see that there are two lines of display is not complete, is due to the setting of the display range of small reasons.

In addition, the ExtTextOut function can also set the spacing of characters, and the third line of the running result is the result of a different set of spacing.

The program also uses the CreateFont function to create a text string in italics and upper right. Using the example above, we present the commonly used text output as an example, as long as a good comparison of the example code, in conjunction with the MSDN instructions, coupled with this series of the first Windows Programming Basic framework, you will be able to master the basic text output of Windows programming.

Focus on the public platform: the Programmer Interaction Alliance (coder_online), you can get the first original technical articles, and (Java/c/c++/android/windows/linux) technology Daniel Friends, online communication programming experience, get programming basics, Solve programming problems. Programmer Interactive Alliance, Developer's own home.

Reproduced please specify the source, thank you for your cooperation!

"Windows Programming" series Third: Text character output

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.