无法将焦点设置到文本框

Cannot set focus to textbox

我正在使用 VB 并尝试 select 将文本的一部分放在单独表单的文本框中。但是,我似乎找不到从其他表单访问文本框的好方法,尽管文本框是 public(我是 VB 的新手)。

目前,我正在尝试通过调用位于表单(带有文本框的表单)中的函数,然后专注于文本框和 selecting/highlighting 文本来实现这一点。但是还是不行:

    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

有了这个,我先隐藏原来的表格,然后尝试select文本,并带回表格。它表明活动表单是我尝试 select 文本的表单,但它 returns 在 CanFocus() 上是错误的。

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

嗯。这比我想象的更繁琐。您需要传递对其他形式的引用:

主要形式:

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
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 个按钮的 "find" 表单,该按钮将突出显示它在另一个表单的 txtNotes 中找到的字符串在 TextBox1 中的第一次出现。如果您还希望它找到空格,请删除 Trim 函数。您可以添加代码以查找其他匹配项或转到 forward/backward.