在我的应用程序中,我有一个用于输入用户名的文本框。如果文本为空,我想显示"在此处输入用户名"在灰色的同一文本框中。文本框中是否有这样的属性。就像在Firefox浏览器中一样,如果URL字段为空,它将显示"转到网站"灰色的
由于
答案 0 :(得分:9)
我知道这可能是一个旧帖子,但我想我会回答它,以防万一其他人偶然发现它。
首先声明以下内容(您可能需要导入System.Runtime.InteropServices
)
<DllImport("user32.dll", CharSet:=CharSet.Auto)> _
Private Shared Function SendMessage(ByVal hWnd As IntPtr, ByVal msg As Integer, ByVal wParam As Integer, <MarshalAs(UnmanagedType.LPWStr)> ByVal lParam As String) As Int32
End Function
然后调用以下内容(根据需要进行更改):
SendMessage(Me.textbox1.Handle, &H1501, 0, "Enter User name here")
答案 1 :(得分:1)
假设您的意思是Windows窗体,请查看this question
基本上,您需要使用EM_SETCUEBANNER
值为控件调用WinAPI SendMessage
函数。
答案 2 :(得分:1)
我非常喜欢CodeProject.com的这个解决方案:http://www.codeproject.com/KB/edit/TextBoxHint.aspx?display=Print
当用户在他/她的文本中输入字段时,光滑的淡出是非常好的。它非常容易实现,看起来很棒。
答案 3 :(得分:1)
你可以继承TextBox并覆盖WndProc
Public Class TextBoxPlaceHolder
Inherits TextBox
Private Const WM_PAINT As Int32 = &HF
Protected Overrides Sub WndProc(ByRef m As System.Windows.Forms.Message)
MyBase.WndProc(m)
If m.Msg = WM_PAINT AndAlso Me.TextLength = 0 Then
Using g = Me.CreateGraphics
g.DrawString("Enter User name here", Me.Font, Brushes.Gray, 1, 1)
End Using
End If
End Sub
End Class
答案 4 :(得分:0)
Ivan和cardmagik的出色作品。 创建一个用户控件并使用以下代码。
Public Class RichTextBoxPlaceHolder
Inherits RichTextBox
Private Const WM_PAINT As Int32 = &HF
Private mstrHint As String = "Enter text"
Protected Overrides Sub WndProc(ByRef m As System.Windows.Forms.Message)
MyBase.WndProc(m)
If m.Msg = WM_PAINT AndAlso Me.TextLength = 0 Then
Using g = Me.CreateGraphics
g.DrawString(mstrHint, Me.Font, Brushes.Gray, 1, 1)
End Using
End If
End Sub
Public Property Hint() As String
Get
Return mstrHint
End Get
Set(ByVal value As String)
mstrHint = value
End Set
End Property
End Class
屏幕截图:
答案 5 :(得分:-1)
尝试以下内容:
(onkeyup)
If TextBox.Text = "" Then
TextBox.Text = "Enter username here..."
TextBox.ForeColor = <your chosen color here>
Else
TextBox.ForeColor = <normal color here>
End If