【问题标题】:DrawText only displays the first callDrawText 只显示第一次调用
【发布时间】:2011-02-19 12:01:49
【问题描述】:

我在 Win32 程序中使用 DrawText 函数在屏幕顶部中心显示“本地”,在中心显示“服务器”。当我运行程序时,它显示“本地”而不是“服务器”。这是我的消息循环中的代码:

case WM_PAINT:
        {
            RECT localLabel;
            localLabel.left = 0;
            localLabel.top = 0;
            localLabel.right = 270;
            localLabel.bottom = 20;
            PAINTSTRUCT localPs;
            HDC localHandle = BeginPaint(hwnd, &localPs);
            DrawText(localHandle, "Local", -1, &localLabel, DT_CENTER);
            EndPaint(hwnd, &localPs);

            PAINTSTRUCT serverPs;
            RECT serverLabel;
            serverLabel.left = 0;
            serverLabel.top = 100;
            serverLabel.right = 270;
            serverLabel.bottom = 20;
            HDC serverHandle = BeginPaint(hwnd, &serverPs);
            DrawText(serverHandle, "Server", -1, &serverLabel, DT_CENTER);
            EndPaint(hwnd, &serverPs);
        }
        break;

我尝试使用相同的 PAINTSTRUCT,但没有帮助。我尝试使用相同的 HDC,但这也无济于事。如何在屏幕上同时显示?

谢谢。

【问题讨论】:

    标签: c++ winapi drawtext


    【解决方案1】:

    您的第二个矩形无效(bottom 应该是 120 而不是 20,因为它是实际的底部坐标,而不是高度)。此外,您必须在调用 EndPaint() 之前渲染这两个字符串:

    PAINTSTRUCT ps;
    HDC hdc = BeginPaint(hwnd, &ps);
    
    RECT localLabel;
    localLabel.left = 0;
    localLabel.top = 0;
    localLabel.right = 270;
    localLabel.bottom = 20;
    DrawText(hdc, "Local", -1, &localLabel, DT_CENTER);
    
    RECT serverLabel;
    serverLabel.left = 0;
    serverLabel.top = 100;
    serverLabel.right = 270;
    serverLabel.bottom = 120;
    DrawText(hdc, "Server", -1, &serverLabel, DT_CENTER);
    
    EndPaint(hwnd, &ps);
    

    最后,顺便说一句,您可能不想将所有代码留在窗口过程的case 语句中。考虑将其移动到自己的函数中以提高可读性(和可维护性)。

    【讨论】:

      【解决方案2】:

      首先,您的bottom 坐标在您的top 上方,这是故意的吗?

      然后,您应该为收到的每个WM_PAINT 拨打一次BeginPaint/EndPaint。它通常是这样的:

      case WM_PAINT:
      {
          PAINTSTRUCT ps;
          HDC localHandle = BeginPaint(hwnd, &ps);
          // do *all* the drawing
          EndPaint(hwnd, &ps);
      }
      break;
      

      【讨论】:

        【解决方案3】:

        "bottom" 就是矩形的底部。您正在使用它,就好像它是高度一样。

        serverLabel.bottom = serverLabel.top + 20;
        

        【讨论】:

        • 文本仍然没有绘制在窗口上,但感谢您指出这一点。
        【解决方案4】:

        在我看来 serverLabel.bottom = 20;应该是 serverLabel.bottom = 120;

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-12-04
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多