获得焦点时选择文本框的内容 [英] Select the content of textbox when it receives focus
问题描述
我在 制作一个类似的问题WinForms TextBox 的行为类似于浏览器的地址栏
现在我正在尝试通过使其通用来对其进行修改或使其更加不同.我想对表单中的所有文本框应用相同的操作,而无需为每个文本框编写代码……我不知道有多少.一旦我在表单中添加了一个文本框,它就应该具有类似的选择动作.
Now i am trying to modify or make it some more different by making it general. I want to apply same action to all the textboxes in form without write code for each one... how many i dun know. As soon as i add a textbox in my form it should behave with similar action of selecting.
那么想知道怎么做?
推荐答案
下面的代码继承自TextBox,实现了你在使 WinForms 文本框的行为类似于浏览器的地址栏.
The following code inherits from TextBox and implements the code you mentioned in Making a WinForms TextBox behave like your browser's address bar.
将 MyTextBox 类添加到项目后,您可以全局搜索 System.Windows.Forms.Text 并替换为 MyTextBox.
Once you've added the MyTextBox class to your project you can do a global search for System.Windows.Forms.Text and replace with MyTextBox.
使用这个类的好处是你不会忘记为每个文本框连接所有的事件.此外,如果您决定对所有文本框进行另一项调整,则可以在一个地方添加该功能.
The advantage of using this class is you can't forget to wire all the events for every textbox. Also if you decide on another tweak for all textboxes you have one place to add the feature.
Imports System
Imports System.Windows.Forms
Public Class MyTextBox
Inherits TextBox
Private alreadyFocused As Boolean
Protected Overrides Sub OnLeave(ByVal e As EventArgs)
MyBase.OnLeave(e)
Me.alreadyFocused = False
End Sub
Protected Overrides Sub OnGotFocus(ByVal e As EventArgs)
MyBase.OnGotFocus(e)
' Select all text only if the mouse isn't down.
' This makes tabbing to the textbox give focus.
If MouseButtons = MouseButtons.None Then
Me.SelectAll()
Me.alreadyFocused = True
End If
End Sub
Protected Overrides Sub OnMouseUp(ByVal mevent As MouseEventArgs)
MyBase.OnMouseUp(mevent)
' Web browsers like Google Chrome select the text on mouse up.
' They only do it if the textbox isn't already focused,
' and if the user hasn't selected all text.
If Not Me.alreadyFocused AndAlso Me.SelectionLength = 0 Then
Me.alreadyFocused = True
Me.SelectAll()
End If
End Sub
End Class
这篇关于获得焦点时选择文本框的内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!