1

My code can now only get text from a textbox. I want to get text from a window, such as from a web page or text file to textbox. How can I do it?

    private void textBox2_MouseMove(object sender, MouseEventArgs e)
    {
        if (!(sender is TextBox)) return;
        var targetTextBox = sender as TextBox;
        if (targetTextBox.TextLength < 1) return;

        var currentTextIndex = targetTextBox.GetCharIndexFromPosition(e.Location);
        var wordRegex = new Regex(@"(\w+)");
        var words = wordRegex.Matches(targetTextBox.Text);
        if (words.Count < 1) return;

        var currentWord = string.Empty;
        for (var i = words.Count - 1; i >= 0; i--)
        {
            if (words[i].Index <= currentTextIndex)
            {
                currentWord = words[i].Value;
                break;
            }
        }

        if (currentWord == string.Empty) return;
        //toolTip1.SetToolTip(targetTextBox, currentWord);
        textBox3.Text = currentWord;
    }
Bridge
  • 29,818
  • 9
  • 60
  • 82
kdr_81
  • 55
  • 8

1 Answers1

0

Taking the question at face value, in full generality, the only way to be able to do this for all possible windows is to screen scrape and use OCR to convert to text. That's because there is no single common interface that all programs use to generate text.

Now, there are things that you can do that will work for many programs. You can use the accessibility or automation APIs. These are the same techniques as used by screen readers. Document can be found here:

As I understand it, UIA is the successor to MSAA and is preferred in new apps.

David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490