キーボード入力の使用

ウィンドウは、キーストローク メッセージと文字メッセージの形式でキーボード入力を受け取ります。 ウィンドウにアタッチされたメッセージ ループには、キーストローク メッセージを対応する文字メッセージに変換するコードが含まれている必要があります。 ウィンドウがクライアント領域にキーボード入力を表示する場合は、次の文字が入力される位置を示すキャレットを作成して表示する必要があります。 次のセクションでは、キーボード入力の受信、処理、および表示に関連するコードについて説明します。

キーストローク メッセージの処理

キーボード フォーカスがあるウィンドウのウィンドウ プロシージャは、ユーザーがキーボードを入力したときにキーストローク メッセージを受け取ります。 キーストローク メッセージは 、WM_KEYDOWNWM_KEYUPWM_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_CHARWM_DEADCHARWM_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 メッセージの処理でこれらの操作 実行できます。 キャレットの詳細については、キャ レットを参照してください。

キーボード入力の表示

このセクションの例では、アプリケーションがキーボードから文字を受け取り、ウィンドウのクライアント領域に表示し、入力された各文字でキャレットの位置を更新する方法を示します。 また、左方向キー、右方向キー、HOME キーストローク、END キーストロークに応答してキャレットを移動する方法を示し、Shift キーと右方向キーの組み合わせに応じて選択したテキストを強調表示する方法も示します。

WM_CREATE メッセージの処理中に、例に示すウィンドウ プロシージャは、キーボード入力を格納するための 64K バッファーを割り当てます。 また、現在読み込まれているフォントのメトリックも取得され、フォント内の文字の高さと平均幅が保存されます。 高さと幅は、クライアント領域のサイズに基づいて行の長さと行の最大数を計算するために、 WM_SIZE メッセージの処理に使用されます。

ウィンドウ プロシージャは、 WM_SETFOCUS メッセージを処理するときにキャレットを作成して表示します。 WM_KILLFOCUS メッセージを処理するときに、キャレットを非表示にして削除します。

WM_CHAR メッセージを処理するとき、ウィンドウ プロシージャは文字を表示し、入力バッファーに格納し、キャレット位置を更新します。 また、ウィンドウ プロシージャはタブ文字を 4 つの連続するスペース文字に変換します。 バックスペース、ラインフィード、およびエスケープ文字はビープ音を生成しますが、それ以外の場合は処理されません。

ウィンドウ・プロシージャーは、 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; 
}