接收焦点时选择文本框的内容 [英] Select the content of textbox when it receives focus
问题描述
我在发现了类似的问题WinForms的TextBox的行为就像你的浏览器的地址栏
现在我正在尝试修改或通过使其一般。我想要在表单中的所有文本框中应用相同的动作,而不用为每个文本编写代码...我知道多少个。只要我在我的表单中添加一个文本框,它应该采取类似的选择行为。
所以想知道如何去做?
从TextBox继承并实现您在制作WinForms文本框像您的浏览器地址栏一样运行。
将MyTextBox类添加到项目后,您可以对System.Windows.Forms.Text进行全局搜索,然后替换为MyTextBox。 b
$ b
使用这个类的好处是你不能忘记连接每个文本框的所有事件。此外,如果您决定对所有文本框进行其他调整,则可以添加该功能。
导入系统
导入System.Windows.Forms
公共类MyTextBox
继承TextBox
私有alreadyFocused作为布尔
受保护的覆盖Sub OnLeave(ByVal e As EventArgs)
MyBase.OnLeave(e)
Me.alreadyFocused = False
保护覆盖Sub OnGotFocus(ByVal e作为EventArgs)
MyBase.OnGotFocus(e)
'仅在鼠标未关闭的情况下选择全部文本。
'这使得标签到文本框给焦点。
如果MouseButtons = MouseButtons.None然后
Me.SelectAll()
Me.alreadyFocused = True
End If
结束Sub
受保护的覆盖Sub OnMouseUp(ByVal mevent As MouseEventArgs)
MyBase.OnMouseUp(mevent)
'像谷歌浏览器这样的浏览器在鼠标上选择文本向上。
'他们只在文本框没有被聚焦的时候做,
',如果用户没有选择所有的文本。
If Not Me.alreadyFocused AndAlso Me.SelectionLength = 0 Then
Me.alreadyFocused = True
Me.SelectAll()
End If
End Sub
End Class
I have found a similar question to mine in Making a WinForms TextBox behave like your browser's address bar
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.
So wondering how to do it?
The following code inherits from TextBox and implements the code you mentioned in Making a WinForms TextBox behave like your browser's address bar.
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屋!