2010-07-08 91 views
3

我发现了一个类似的问题在Making a WinForms TextBox behave like your browser's address bar选择文本框的内容

我现在想修改或使一些通过使不同一般我的。我想在表单中的所有文本框中应用相同的动作,而无需为每个文本编写代码......我知道多少。只要我在我的表单中添加一个文本框,它应该采取类似的选择行为。

想知道该怎么做?

+0

Windows窗体? Web窗体?什么? – 2010-07-08 06:07:50

+0

它是windows窗体 – KoolKabin 2010-07-08 06:17:36

回答

7

下面的代码从文本框中继承并实现你Making a WinForms TextBox behave like your browser's address bar提到的代码。

将MyTextBox类添加到项目后,您可以对System.Windows.Forms.Text执行全局搜索,并使用MyTextBox进行替换。

使用这个类的好处是你不能忘记连接每个文本框的所有事件。另外,如果您决定对所有文本框进行其他调整,则可以在一个位置添加该功能。

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 
+0

好吧,这个把戏会更有效地完成我的任务 – KoolKabin 2010-07-08 12:18:03

3

假设您要使用您链接到的问题所接受的解决方案,您只需创建一个新的文本框就可以使用AddHandler将相同的3个事件处理程序添加到每个新的文本框。

然后,您需要更改事件处理程序,而不是将文本框引用为this.textBox1,他们会将其引用为CType(sender, TextBox),这意味着它们将使用生成该事件的文本框。

编辑:我来补充该行的代码在这里也因为它更易于阅读,然后

Private Sub TextBox_GotFocus (ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox1.GotFocus, TextBox2.GotFocus, TextBox3.GotFocus 
+0

hm ...挺有意思的......我试过了......它甚至可以......但是我们可以在窗体上做些什么,以便我们需要添加事件处理程序给他们 – KoolKabin 2010-07-08 07:34:05

+0

@KoolKabin:我想过你的意思是你动态添加文本框?否则,如果它们是在设计器中创建的,则可以将它们全部链接到相同的事件处理程序,如下所示:Private Sub TextBox_GotFocus(ByVal sender As System.Object,ByVal e As System.EventArgs)处理TextBox1.GotFocus,TextBox2.GotFocus ,TextBox3.GotFocus' – 2010-07-08 07:50:09

+0

thnx它的工作。我们可以在表单级别事件上探索一步吗? – KoolKabin 2010-07-08 09:10:09

1

我们使用这个定制的TextBox控件:

Public Class TextBoxX 
    Inherits System.Windows.Forms.TextBox 

    Private Sub TextBoxX_MouseUp(sender As Object, e As MouseEventArgs) Handles Me.MouseUp 
     SelectAll() 
    End Sub 
end class 

你可以看到我们的TextBox的全部项目(类固醇)在GitHub上https://github.com/logico-dev/TextBoxX