使用键盘输入
窗口以击键消息和字符消息的形式接收键盘输入。 附加到窗口的消息循环必须包含代码,才能将击键消息转换为相应的字符消息。 如果窗口在其工作区中显示键盘输入,它应创建并显示插入点以指示将输入下一个字符的位置。 以下部分介绍接收、处理和显示键盘输入所涉及的代码:
处理击键消息
具有键盘焦点的窗口的窗口过程在用户键入键盘时接收击键消息。 击键消息是 WM_KEYDOWN、 WM_KEYUP、 WM_SYSKEYDOWN和 WM_SYSKEYUP。 典型的窗口过程会忽略 除WM_KEYDOWN之外的所有击键消息。 当用户按下键时,系统会发布 WM_KEYDOWN 消息。
当窗口过程收到 WM_KEYDOWN 消息时,它应检查消息附带的虚拟键代码,以确定如何处理击键。 虚拟密钥代码位于消息的 wParam 参数中。 通常,应用程序只处理非字符键生成的击键,包括函数键、游标移动键以及 INS、DEL、HOME 和 END 等特殊用途键。
以下示例显示了典型应用程序用来接收和处理击键消息的窗口过程框架。
case WM_KEYDOWN:
switch (wParam)
{
case VK_LEFT:
// Process the LEFT ARROW key.
break;
case VK_RIGHT:
// Process the RIGHT ARROW key.
break;
case VK_UP:
// Process the UP ARROW key.
break;
case VK_DOWN:
// Process the DOWN ARROW key.
break;
case VK_HOME:
// Process the HOME key.
break;
case VK_END:
// Process the END key.
break;
case VK_INSERT:
// Process the INS key.
break;
case VK_DELETE:
// Process the DEL key.
break;
case VK_F2:
// Process the F2 key.
break;
// Process other non-character keystrokes.
default:
break;
}
翻译字符消息
从用户接收字符输入的任何线程都必须在其消息循环中包含 TranslateMessage 函数。 此函数检查击键消息的虚拟键代码,如果代码对应于字符,将字符消息置于消息队列中。 在消息循环的下一次迭代中删除并调度字符消息;消息的 wParam 参数包含字符代码。
通常,线程的消息循环应使用 TranslateMessage 函数来翻译每条消息,而不仅仅是虚拟键消息。 尽管 TranslateMessage 对其他类型的消息没有影响,但它保证键盘输入正确转换。 以下示例演示如何在典型的线程消息循环中包含 TranslateMessage 函数。
MSG msg;
BOOL bRet;
while (( bRet = GetMessage(&msg, (HWND) NULL, 0, 0)) != 0)
{
if (bRet == -1);
{
// handle the error and possibly exit
}
else
{
if (TranslateAccelerator(hwndMain, haccl, &msg) == 0)
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
}
处理字符消息
当 TranslateMessage 函数转换对应于字符键的虚拟键代码时,窗口过程会收到字符消息。 字符消息是 WM_CHAR、 WM_DEADCHAR、 WM_SYSCHAR和 WM_SYSDEADCHAR。 典型的窗口过程会忽略 除WM_CHAR以外的所有字符消息。 当用户按下以下任一键时, TranslateMessage 函数将生成 WM_CHAR 消息:
- 任何字符键
- Backspace
- ENTER (回车)
- ESC
- SHIFT+Enter (换行符)
- Tab
当窗口过程收到 WM_CHAR 消息时,它应检查消息附带的字符代码以确定如何处理字符。 字符代码位于消息的 wParam 参数中。
以下示例显示了典型应用程序用来接收和处理字符消息的窗口过程框架。
case WM_CHAR:
switch (wParam)
{
case 0x08:
// Process a backspace.
break;
case 0x0A:
// Process a linefeed.
break;
case 0x1B:
// Process an escape.
break;
case 0x09:
// Process a tab.
break;
case 0x0D:
// Process a carriage return.
break;
default:
// Process displayable characters.
break;
}
使用插入符号
接收键盘输入的窗口通常显示用户在窗口的工作区中键入的字符。 窗口应使用插入符号来指示下一个字符将出现在工作区中的位置。 窗口还应在收到键盘焦点时创建和显示插入符号,并在失去焦点时隐藏和销毁插入符号。 窗口可以在 处理WM_SETFOCUS 和 WM_KILLFOCUS 消息时执行这些操作。 有关插入符号的详细信息,请参阅 Carets。
显示键盘输入
本部分中的示例显示了应用程序如何从键盘接收字符、在窗口的工作区中显示字符,以及更新键入每个字符的插入点的位置。 它还演示了如何移动插入符号以响应向左键、向右键、开始键和结束击键,并演示如何突出显示所选文本以响应 Shift+向右键组合。
在处理 WM_CREATE 消息期间,示例中所示的窗口过程分配用于存储键盘输入的 64K 缓冲区。 它还检索当前加载的字体的指标,保存字体中字符的高度和平均宽度。 高度和宽度用于处理 WM_SIZE 消息,根据工作区的大小计算行长度和最大行数。
窗口过程在处理 WM_SETFOCUS 消息时创建并显示插入符号。 处理 WM_KILLFOCUS 消息时,它会隐藏和删除插入点。
处理 WM_CHAR 消息时,窗口过程会显示字符,将它们存储在输入缓冲区中,并更新插入点位置。 窗口过程还会将制表符转换为四个连续空格字符。 后空、换行符和转义字符会生成蜂鸣声,但不进行其他处理。
当处理 WM_KEYDOWN 消息时,窗口过程执行左、右、端和家庭插入点移动。 处理向右键的操作时,窗口过程会检查 SHIFT 键的状态,如果关闭,请在插入点移动时选择插入点右侧的字符。
请注意,编写以下代码,以便可以编译为 Unicode 或 ANSI。 如果源代码定义 UNICODE,字符串将作为 Unicode 字符进行处理;否则,它们将作为 ANSI 字符进行处理。
#define BUFSIZE 65535
#define SHIFTED 0x8000
LONG APIENTRY MainWndProc(HWND hwndMain, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
HDC hdc; // handle to device context
TEXTMETRIC tm; // structure for text metrics
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; // 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
TCHAR szBuf[128]; // temporary buffer
TCHAR 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
size_t * pcch;
HRESULT hResult;
switch (uMsg)
{
case WM_CREATE:
// Get the metrics of the 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 = (LPTSTR) GlobalAlloc(GPTR,
BUFSIZE * sizeof(TCHAR));
return 0;
case WM_SIZE:
// Save the new width 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:
// check if current location is close enough to the
// end of the buffer that a buffer overflow may
// occur. If so, add null and display contents.
if (cch > BUFSIZE-5)
{
pchInputBuf[cch] = 0x00;
SendMessage(hwndMain, WM_PAINT, 0, 0);
}
switch (wParam)
{
case 0x08: // backspace
case 0x0A: // linefeed
case 0x1B: // escape
MessageBeep((UINT) -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 = (TCHAR) wParam;
HideCaret(hwndMain);
// Retrieve the character's width and output
// the character.
hdc = GetDC(hwndMain);
GetCharWidth32(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
// The 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);
GetCharWidth32(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 whether 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.
GetCharWidth32(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((UINT) -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] = TEXT('\0');
// Retrieve the text extent and use it
// to set the horizontal position of the
// caret.
hdc = GetDC(hwndMain);
hResult = StringCchLength(szBuf, 128, pcch);
if (FAILED(hResult))
{
// TODO: write error handler
}
GetTextExtentPoint32(hdc, szBuf, *pcch,
&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, and 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;
}