使用Bitmap创建Caret无显示且无报错问题求助(附代码)
问题:使用Bitmap创建Caret但无法显示
我参考微软文档中「处理键盘输入」章节的WM_SETFOCUS代码段,修改为用Bitmap创建Caret,但屏幕上看不到任何Caret图像,且CreateCaret()函数未返回错误信息。我已确认Bitmap已成功创建,最初的代码如下:
case WM_SETFOCUS: { int caret_width = (nCharX/5)>=2 ? nCharX/5 : 2; RECT rcCaret = { 0, 0, caret_width, nCharY }; hdc = GetDC(hwnd); HBITMAP hBitmapNew = CreateCompatibleBitmap(hdc, caret_width, nCharY); HDC hdcMemNew = CreateCompatibleDC(hdc); SelectObject(hdcMemNew, hBitmapNew); HBRUSH caretBrush = CreateSolidBrush(RGB(255,0,0)); FillRect(hdcMemNew, &rcCaret, caretBrush); if(CreateCaret(hwnd, (HBITMAP) hBitmapNew, 0, 0)==0) { MessageBox(NULL, "CreateCaret() error!", "Error", MB_OK) ; } // CreateCaret(hwnd, 0, nCharX, nCharY); // Adjust the caret position. SetCaretPos(nCaretPosX * nCharX, nCaretPosY * nCharY); // Display the caret. ShowCaret(hwnd); DeleteObject(caretBrush); DeleteObject(hdcMemNew); DeleteObject(hBitmapNew); ReleaseDC(hwnd, hdc); } break;
我尝试修改Caret的Bitmap,但窗口上仍无Caret图像。后来意识到Bitmap变量不应被删除,将其改为全局变量后的最新代码如下,问题仍未解决,恳请帮忙:
HBITMAP hBitmap; // Global variable case WM_SETFOCUS: { int caret_width = (nCharX/5)>=2 ? nCharX/5 : 2; RECT rcCaret = { 0, 0, caret_width, nCharY }; hdc = GetDC(hwnd); HDC hdcMem = CreateCompatibleDC(hdc); hBitmap = CreateCompatibleBitmap(hdc, caret_width, nCharY); HBITMAP hBitmapOld = (HBITMAP) SelectObject(hdcMem, hBitmap); // To get a red colored caret, we can use the result of XOR operation // between the background color and the red color as the bitmap color. HBRUSH caretBrush = CreateSolidBrush(RGB(236, 236, 236) ^ RGB(255, 0, 0)); FillRect(hdcMem, &rcCaret, caretBrush); if(CreateCaret(hwnd, (HBITMAP) hBitmap, 0, 0)==0) { MessageBox(NULL, "CreateCaret() error!", "Error", MB_OK) ; } SetCaretPos(nCaretPosX * nCharX, nCaretPosY * nCharY); ShowCaret(hwnd); DeleteObject(caretBrush); DeleteObject(hdcMem); SelectObject(hdcMem, hBitmapOld); ReleaseDC(hwnd, hdc); }
内容的提问来源于stack exchange,提问作者Niteya
相关产品推荐
相关产品推荐

