36.2.5 Example: Displaying Keyboard Input

The example in this section shows how to receive characters from the keyboard, display them in the client area of a window, and update the position of the caret with each character entered. It also demonstrates how to move the cursor in response to the LEFT, RIGHT, HOME and END keystrokes, and shows how to highlight selected text in response to the SHIFT+RIGHT key combination.

During the WM_CREATE message, the window procedure shown in the example allocates a 64KB buffer for storing keyboard input. It also retrieves the metrics of the currently loaded font, saving the height and average width of characters in the font. The height and width are used during the WM_SIZE message to calculate the line length and maximum number of lines, based on the size of the client area.

The window procedure creates and displays the caret during the WM_SETFOCUS message. It hides and deletes the caret during the WM_KILLFOCUS message.

During the WM_CHAR message, the window procedure displays characters, stores them in the input buffer, and updates the caret position. Tab characters are converted to four consecutive space characters. Backspace, line feed, and escape characters generate a beep but are not otherwise processed.

The window procedure performs the left, right, end, and home caret movement operations during the WM_KEYDOWN message. While processing the RIGHT key, the window procedure checks the state of the SHIFT key and, if it is down, highlights the character to the right of the caret as the caret is moved.

#define BUFSIZE 65535

#define SHIFTED 0x8000

LONG APIENTRY MainWndProc(hwndMain, uMsg, wParam, lParam)

HWND hwndMain;

UINT uMsg;

UINT wParam;

LONG lParam;

{

HDC hdc;

TEXTMETRIC tm; /* device context */

static DWORD dwCharX; /* average width of characters */

static DWORD dwCharY; /* height of characters */

static DWORD dwClientX; /* width of client area */

static DWORD dwClientY; /* height of client area */

static DWORD dwLineLen; /* line length */

static DWORD dwLines; /* text lines in client area */

static int nCaretPosX = 0; /* horizontal position of caret */

static int nCaretPosY = 0; /* vertical position of caret */

static int nCharWidth = 0; /* width of a character */

static int cch = 0; /* characters in buffer */

static int nCurChar = 0; /* index of current character */

static PTCHAR pchInputBuf; /* address of input buffer */

int i, j; /* loop counters */

int cCR = 0; /* count of carriage returns */

int nCRIndex = 0; /* index of last carriage return */

int nVirtKey; /* virtual-key code */

char szBuf[128]; /* temporary buffer */

char ch; /* current character */

PAINTSTRUCT ps; /* required by BeginPaint */

RECT rc; /* output rectangle for DrawText */

SIZE sz; /* string dimensions */

COLORREF crPrevText; /* previous text color */

COLORREF crPrevBk; /* previous background color */

switch (uMsg) {

case WM_CREATE:

/* Get metrics of current font. */

hdc = GetDC(hwndMain);

GetTextMetrics(hdc, &tm);

ReleaseDC(hwndMain, hdc);

/* Save the average character width and height. */

dwCharX = tm.tmAveCharWidth;

dwCharY = tm.tmHeight;

/* Allocate a buffer to store keyboard input. */

pchInputBuf = (LPSTR) GlobalAlloc(GPTR,

BUFSIZE * sizeof(TCHAR));

return 0;

case WM_SIZE:

/* Save the new widht and height of the client area. */

dwClientX = LOWORD(lParam);

dwClientY = HIWORD(lParam);

/*

* Calculate the maximum width of a line and the

* maximum number of lines in the client area.

*/

dwLineLen = dwClientX - dwCharX;

dwLines = dwClientY / dwCharY;

break;

case WM_SETFOCUS:

/*

* Create, position, and display the caret when the

* window receives the keyboard focus.

*/

CreateCaret(hwndMain, (HBITMAP) 1, 0, dwCharY);

SetCaretPos(nCaretPosX, nCaretPosY * dwCharY);

ShowCaret(hwndMain);

break;

case WM_KILLFOCUS:

/*

* Hide and destroy the caret when the window loses the

* keyboard focus.

*/

HideCaret(hwndMain);

DestroyCaret();

break;

case WM_CHAR:

switch (wParam) {

case 0x08: /* backspace */

case 0x0A: /* line feed */

case 0x1B: /* escape */

MessageBeep(-1);

return 0;

case 0x09: /* tab */

/* Convert tabs to four consecutive spaces. */

for (i = 0; i < 4; i++)

SendMessage(hwndMain, WM_CHAR, 0x20, 0);

return 0;

case 0x0D: /* carriage return */

/*

* Record the carriage return and position the

* caret at the beginning of the new line.

*/

pchInputBuf[cch++] = 0x0D;

nCaretPosX = 0;

nCaretPosY += 1;

break;

default: /* displayable character */

ch = (char) wParam;

HideCaret(hwndMain);

/*

* Retrieve the character's width. Output the

* character.

*/

hdc = GetDC(hwndMain);

GetCharWidth(hdc, (UINT) wParam, (UINT) wParam,

&nCharWidth);

TextOut(hdc, nCaretPosX, nCaretPosY * dwCharY,

&ch, 1);

ReleaseDC(hwndMain, hdc);

/* Store the character in the buffer. */

pchInputBuf[cch++] = ch;

/*

* Calculate the new horizontal position of the

* caret. If the position exceeds the maximum,

* insert a carriage return and move the caret

* to the beginning of the next line.

*/

nCaretPosX += nCharWidth;

if ((DWORD) nCaretPosX > dwLineLen) {

nCaretPosX = 0;

pchInputBuf[cch++] = 0x0D;

++nCaretPosY;

}

nCurChar = cch;

ShowCaret(hwndMain);

break;

}

SetCaretPos(nCaretPosX, nCaretPosY * dwCharY);

break;

case WM_KEYDOWN:

switch (wParam) {

case VK_LEFT:/* left arrow */

/*

* Caret can move only to the beginning of the

* current line.

*/

if (nCaretPosX > 0) {

HideCaret(hwndMain);

/*

* Retrieve the character to the left of

* the caret, calculate the character's

* width, then subtract the width from the

* current horizontal position of the caret

* to obtain the new position.

*/

ch = pchInputBuf[--nCurChar];

hdc = GetDC(hwndMain);

GetCharWidth(hdc, ch, ch, &nCharWidth);

ReleaseDC(hwndMain, hdc);

nCaretPosX = max(nCaretPosX - nCharWidth,

0);

ShowCaret(hwndMain);

}

break;

case VK_RIGHT:/* right arrow */

/*

* Caret moves to the right or, when a carriage

* return is encountered, to the beginning of

* the next line.

*/

if (nCurChar < cch) {

HideCaret(hwndMain);

/*

* Retrieve the character to the right of

* the caret. If it's a carriage return,

* position the caret at the beginning of

* the next line.

*/

ch = pchInputBuf[nCurChar];

if (ch == 0x0D) {

nCaretPosX = 0;

nCaretPosY++;

}

/*

* If the character isn't a carriage

* return, check to see if the SHIFT key is

* down. If it is, invert the text colors

* and output the character.

*/

else {

hdc = GetDC(hwndMain);

nVirtKey = GetKeyState(VK_SHIFT);

if (nVirtKey & SHIFTED) {

crPrevText = SetTextColor(hdc,

RGB(255, 255, 255));

crPrevBk = SetBkColor(hdc,

RGB(0,0,0));

TextOut(hdc, nCaretPosX,

nCaretPosY * dwCharY,

&ch, 1);

SetTextColor(hdc, crPrevText);

SetBkColor(hdc, crPrevBk);

}

/*

* Get the width of the character and

* calculate the new horizontal

* position of the caret.

*/

GetCharWidth(hdc, ch, ch, &nCharWidth);

ReleaseDC(hwndMain, hdc);

nCaretPosX = nCaretPosX + nCharWidth;

}

nCurChar++;

ShowCaret(hwndMain);

break;

}

break;

case VK_UP:/* up arrow */

case VK_DOWN:/* down arrow */

MessageBeep(-1);

return 0;

case VK_HOME:/* home */

/*

* Set the caret's position to the upper left

* corner of the client area.

*/

nCaretPosX = nCaretPosY = 0;

nCurChar = 0;

break;

case VK_END:/* end */

/* Move the caret to the end of the text. */

for (i=0; i < cch; i++) {

/*

* Count the carriage returns and save the

* index of the last one.

*/

if (pchInputBuf[i] == 0x0D) {

cCR++;

nCRIndex = i + 1;

}

}

nCaretPosY = cCR;

/*

* Copy all text between the last carriage

* return and the end of the keyboard input

* buffer to a temporary buffer.

*/

for (i = nCRIndex, j=0; i < cch; i++, j++)

szBuf[j] = pchInputBuf[i];

szBuf[j] = '\0';

/*

* Retrieve the extent of the text. Use the

* extent to set the horizontal position of the

* caret.

*/

hdc = GetDC(hwndMain);

GetTextExtentPoint(hdc, szBuf, lstrlen(szBuf),

&sz);

nCaretPosX = sz.cx;

ReleaseDC(hwndMain, hdc);

nCurChar = cch;

break;

default:

break;

}

SetCaretPos(nCaretPosX, nCaretPosY * dwCharY);

break;

case WM_PAINT:

if (cch == 0) /* nothing in input buffer */

break;

hdc = BeginPaint(hwndMain, &ps);

HideCaret(hwndMain);

/*

* Set the clipping rectangle, then draw the text into

* it.

*/

SetRect(&rc, 0, 0, dwLineLen, dwClientY);

DrawText(hdc, pchInputBuf, -1, &rc, DT_LEFT);

ShowCaret(hwndMain);

EndPaint(hwndMain, &ps);

break;

.

. /* Process other messages. */

.

case WM_DESTROY:

PostQuitMessage(0);

/* Free the input buffer. */

GlobalFree((HGLOBAL) pchInputBuf);

UnregisterHotKey(hwndMain, 0xAAAA);

break;

default:

return (DefWindowProc(hwndMain, uMsg, wParam, lParam));

}

return NULL;

}