无法将焦点设置为文本框

时间:2016-11-13 23:57:23

标签: vb.net winforms textbox focus highlight

我正在使用VB并尝试在单独表单的文本框中选择文本的一部分。但是,我似乎找不到从其他表单访问文本框的好方法,虽然文本框是公开的(我是VB新手)。

目前,我尝试通过调用位于表单中的函数(带有文本框的表单),然后关注文本框并选择/突出显示文本来尝试这样做。但它仍然无法运作:

    Public Sub GetFindLoc(ByVal lngStart As Long, ByVal intLen As Integer)
        frmFind.Hide()
        MessageBox.Show(ActiveForm.Name)
        MessageBox.Show(txtNotes.CanFocus())
        txtNotes.Focus()
        txtNotes.Select(lngStart, intLen)
        frmFind.Show()
    End Sub

有了这个,我首先隐藏原始表单,然后尝试选择文本,然后将表单带回来。它显示活动表单是我尝试选择文本的表单,但它在CanFocus()上返回false。

任何帮助将不胜感激,谢谢!

2 个答案:

答案 0 :(得分:1)

嗯。这比我想象的更加繁琐。您需要将引用传递给另一个表单:

主要形式:

Public Class frmNotes
  'This is the main form
  'This form has a textbox named txtNotes and a button called btnShowFind
  'txtNotes has .MultiLine=True

  Private mfrmFind As frmFind
  Private Sub btnShowFind_Click(sender As Object, e As EventArgs) Handles btnShowFind.Click
    If mfrmFind Is Nothing OrElse mfrmFind.IsDisposed Then
      mfrmFind = New frmFind(Me)
      mfrmFind.Show()
    Else
      mfrmFind.BringToFront()
    End If
  End Sub
End Class

Finder表格:

Public Class frmFind
  'This form has a textbox called txtFind and a button called btnFind
  Private mfrmParent As frmNotes
  Sub New(parent As frmNotes)

    ' This call is required by the designer.
    InitializeComponent()

    ' Add any initialization after the InitializeComponent() call.
    mfrmParent = parent
  End Sub

  Private Sub btnFind_Click(sender As Object, e As EventArgs) Handles btnFind.Click
    If txtFind.Text = "" Then
      MsgBox("Please enter text to find", MsgBoxStyle.Exclamation)
      Exit Sub
    End If
    Dim intSearchBegin As Integer = mfrmParent.txtNotes.SelectionStart + 1
    Dim intStart As Integer = mfrmParent.txtNotes.Text.IndexOf(txtFind.Text, intSearchBegin)
    If intStart > -1 Then
      mfrmParent.txtNotes.Select(intStart, txtFind.Text.Length)
      mfrmParent.txtNotes.Focus()
      mfrmParent.BringToFront()
    Else
      mfrmParent.txtNotes.Select(0, 0)
      MsgBox("No more matches")
    End If
  End Sub
End Class

答案 1 :(得分:0)

Public Class frmFind

    Private Sub btnFind_Click(sender As Object, e As EventArgs) Handles btnFind.Click

        Dim search As String = TextBox1.Text.Trim
        Dim pos As Integer = frmNotes.txtNotes.Text.IndexOf(search)

        If pos > 0 Then
            frmNotes.txtNotes.Focus()
            frmNotes.txtNotes.Select(pos, search.Length)
        End If

    End Sub

End Class

这只是一个"发现"带有1个文本框和1个按钮的表单,它将突出显示在TextBox1中第一次出现的字符串,它在另一个表单的txtNotes中找到。如果您希望它也能找到空格,请删除Trim函数。您可以添加代码以查找其他事件或前进/后退。