【问题标题】:SetBkColor and SetTextColor Don't set the background and text color for DrawTextSetBkColor 和 SetTextColor 不要为 DrawText 设置背景和文本颜色
【发布时间】:2011-07-09 10:24:08
【问题描述】:

使用以下代码将字符串写入 DesktopWindow 的设备上下文可以工作,但背景颜色和文本颜色保持不变(蓝底白字):

Private Sub writeToScreen(txt As String)
Declare Function GetDesktopWindow Lib "user32" () As Integer
Declare Function DrawTextW Lib "user32" (hdc As Integer, lpStr As WString, nCount As Integer, _
     ByRef lpRect As RECT, wFormat As Integer) As Integer
Declare Function CreateDCA Lib "gdi32" (lpDriverName As CString, lpDeviceName As Integer, _
     lpOutput As Integer, lpInitData As Integer) As Integer
Declare Function DeleteDC Lib "gdi32" (hdc As Integer) As Integer
Declare Function GetTextColor Lib "gdi32" (hdc As Integer) As Color
Declare Function SetTextColor Lib "gdi32" (hdc As Integer,  crColor As Color) As Color
Declare Function GetBkColor Lib "gdi32" (hdc As Integer) As Color
Declare Function SetBkColor  Lib "gdi32" (hdc As Integer,  crColor As Color) As Color

Const DT_MULTILINE = &H00000001
Const DT_NOCLIP = &H100
Const INVALID_COLOR = &hFFFFFFFF

Dim tFormat As Integer = DT_MULTILINE Or DT_NOCLIP
Dim hdc As Integer = CreateDCA("DISPLAY", 0, 0, 0)
Dim tRect As RECT   //The RECT structure is defined elsewhere
Dim textCol, backColor As Color

tR.Left = 200
tR.Top = 250
tR.Right = 600
tR.Bottom = 350
textCol = SetTextColor(hdc, &cFF8040)
backColor = SetBkColor(hdc, &c000000)

If DrawTextW(hdc, txt, Len(txt), tR, tFormat) = 0 Then
  System.DebugLog("Text Draw Error")
End If

Call SetTextColor(hdc, textCol)
Call SetBkColor(hdc, backColor)
Call DeleteDC(hdc)  
End Sub

我做错了什么?文字写得很好,但颜色很难看。

【问题讨论】:

  • 你做错的主要事情是直接在桌面上绘图。你应该永远这样做。您不拥有桌面窗口。 Windows 拥有桌面窗口。正如您在蹒跚学步时所学的那样,您不应该偷窃和破坏您不拥有的东西。现在,重新设计您的应用程序。
  • 使用 Graphics.FromHdc() 和 TextRenderer.DrawText() 代替。
  • @Cody Gray 没有争论,但这不是我问的。
  • 嗯,我看到最初的评论是从这个级别的流鼻血开始的,大概是抽象的。但这不仅仅是抽象的讲道。 您不应该这样做有非常真实的原因。我也意识到这不是你问的。从技术上讲,这就是为什么我将其发布为评论,而不是答案。但更重要的是,在推进这个项目之前,您应该强烈考虑这是非常真实的建议。即使你让它“工作”,你也会遇到更大的问题。知道这一点似乎总是很高兴。
  • 我希望人们过去曾多次阻止我并告诉我“你做错了”。最好是早点而不是晚点。在 Stack Overflow 上看到这么多反对该建议的用户真是太棒了。如果您不是从经验丰富的开发人员那里寻求合理的建议,那么也许您会对 rentacoder.com 这样的网站更感兴趣?

标签: windows winapi desktop gdi realbasic


【解决方案1】:

首先使用 SetBkMode() (http://msdn.microsoft.com/en-us/library/dd162965%28v=vs.85%29.aspx) 将 DC 设置为不绘制背景。

SetTextColor() 仅用于 TextOut(),而不是 DrawText(),IIRC - MSDN 对此有歧义。尝试在 DC 中选择不同的 HBRUSH,这可能会满足您的需求。

【讨论】:

    猜你喜欢
    • 2011-02-14
    • 2013-07-29
    • 1970-01-01
    • 2018-02-27
    • 2017-09-04
    • 2021-12-03
    • 2017-06-08
    • 2019-09-09
    • 1970-01-01
    相关资源
    最近更新 更多