英語で読む

次の方法で共有


RichTextBox.GetCharIndexFromPosition(Point) メソッド

定義

指定位置に最も近い文字のインデックスを取得します。

C#
public int GetCharIndexFromPosition(System.Drawing.Point pt);
C#
public override int GetCharIndexFromPosition(System.Drawing.Point pt);

パラメーター

pt
Point

検索する位置。

戻り値

指定した位置の 0 から始まる文字インデックス。

次のコード例では、 メソッドと メソッドをGetCharIndexFromPosition使用してコントロール内の特定の文字列を検索し、見つかった文字列がコントロール内RichTextBoxにある文字インデックスを表示する方法をRichTextBoxFindします。 この例では、コントロールの内容内で "brown" という単語を検索し、検索文字列が見つかった文字インデックス位置を返します。 この例では、テキストを含む という名前richTextBox1のコントロールをRichTextBox含むフォームが必要です。 また、この例のコードが のイベントRichTextBoxMouseDown接続されている必要もあります。

C#
private void richTextBox1_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e)
{
    // Declare the string to search for in the control.
    string searchString = "brown";

    // Determine whether the user clicks the left mouse button and whether it is a double click.
    if (e.Clicks == 1 && e.Button == MouseButtons.Left)
    {
        // Obtain the character index where the user clicks on the control.
        int positionToSearch = richTextBox1.GetCharIndexFromPosition(new Point(e.X, e.Y));
        // Search for the search string text within the control from the point the user clicked.
        int textLocation = richTextBox1.Find(searchString, positionToSearch, RichTextBoxFinds.None);

        // If the search string is found (value greater than -1), display the index the string was found at.
        if (textLocation >= 0)
            MessageBox.Show("The search string was found at character index " + textLocation.ToString() + ".");
        else
            // Display a message box alerting the user that the text was not found.
            MessageBox.Show("The search string was not found within the text of the control.");
    }
}

注釈

このメソッドは、 パラメーターで指定された位置に最も近い文字インデックスを pt 返します。 文字インデックスは、スペースを含む、コントロール内のテキストの 0 から始まるインデックスです。 このメソッドを使用すると、マウス座標をこのメソッドに渡すことで、ユーザーがマウスを置いたテキスト内の場所を確認できます。 これは、ユーザーがコントロールのテキスト内の単語の上にマウス ポインターを置いたときにタスクを実行する場合に便利です。

適用対象

製品 バージョン
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
Windows Desktop 3.0, 3.1, 5, 6, 7, 8, 9, 10

こちらもご覧ください