问题描述
我正在 VB.NET 中开发 Windows 窗体应用程序,我目前正在使用标签和文本框制作登录屏幕.
I'm working on a Windows Forms application in VB.NET and I am currently making a login screen using labels and TextBoxes.
我需要的是 TextBox 控件中的 Placeholder,您可以在下面看到 ↓(显然不是我的)
What I need is the Placeholder in TextBox controls you can see below ↓ (not mine obviously)
TextBox
中是否有任何属性允许我将默认占位符(占位符、水印、提示、提示)设置为我想要的?如果没有,我该如何以不同的方式解决这个问题?
Is there any property in TextBox
that allows me to set the default placeholder (placeholder, watermark, hint, tip) to what I want it to be?If there is not any, how can i solve this differently?
推荐答案
使用 EM_SETCUEBANNER
您可以在 this 中找到此方法的 C# 实现发布.
通过发送EM_SETCUEBANNER
到 TextBox
,您可以设置文本提示或提示,由编辑控件显示以提示用户输入信息.
By sending EM_SETCUEBANNER
to a TextBox
, you can set the textual cue, or tip, that is displayed by the edit control to prompt the user for information.
Imports System
Imports System.Runtime.InteropServices
Imports System.Windows.Forms
Public Class MyTextBox
Inherits TextBox
Private Const EM_SETCUEBANNER As Integer = &H1501
<DllImport("user32.dll", CharSet:=CharSet.Auto)>
Private Shared Function SendMessage(ByVal hWnd As IntPtr, ByVal msg As Integer, _
ByVal wParam As Integer, ByVal lParam As String) As Int32
End Function
Protected Overrides Sub OnHandleCreated(e As EventArgs)
MyBase.OnHandleCreated(e)
If Not String.IsNullOrEmpty(CueBanner) Then UpdateCueBanner()
End Sub
Private m_CueBanner As String
Public Property CueBanner As String
Get
Return m_CueBanner
End Get
Set(ByVal value As String)
m_CueBanner = value
UpdateCueBanner()
End Set
End Property
Private Sub UpdateCueBanner()
SendMessage(Me.Handle, EM_SETCUEBANNER, 0, CueBanner)
End Sub
End Class
处理 WM_PAINT
您可以在 this 中找到此方法的 C# 实现发布.
如果您使用 EM_SETCUEBANNER,提示将始终以系统默认颜色显示.当 TextBox 为 MultiLine 时,也不会显示提示.
If you use EM_SETCUEBANNER, the hint always will be shown in a system default color. Also the hint will not be shown when the TextBox is MultiLine.
使用绘画解决方案,您可以使用您想要的任何颜色显示文本.控件多行时也可以显示水印
Using the painting solution, you can show the text with any color that you want. You also can show the watermark when the control is multi-line
Imports System.Drawing
Imports System.Windows.Forms
Public Class ExTextBox
Inherits TextBox
Private m_Hint As String
Public Property Hint As String
Get
Return m_Hint
End Get
Set(ByVal value As String)
m_Hint = value
Me.Invalidate()
End Set
End Property
Protected Overrides Sub WndProc(ByRef m As Message)
MyBase.WndProc(m)
If m.Msg = &HF Then
If Not Me.Focused AndAlso String.IsNullOrEmpty(Me.Text) _
AndAlso Not String.IsNullOrEmpty(Me.Hint) Then
Using g = Me.CreateGraphics()
TextRenderer.DrawText(g, Me.Hint, Me.Font, Me.ClientRectangle, _
SystemColors.GrayText, Me.BackColor, _
TextFormatFlags.Top Or TextFormatFlags.Left)
End Using
End If
End If
End Sub
End Class
这篇关于使用VB.NET的Window Forms中TextBox中的占位符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!