首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> ASP.NET 基礎 >> 關於ASP.NET

如何取得 TextBox 游標位置 (WinForms)

     編輯:關於ASP.NET

SelectionStart 在反向選取時回傳錯誤值。正確做法呼叫 Win32 API GetCaretPos 取得螢幕座標,再轉換為字元索引。

完整程式碼

using System.Runtime.InteropServices;
using System.Drawing;
using System.Windows.Forms;

public partial class Form1 : Form
{
    [DllImport("user32.dll")]
    private static extern bool GetCaretPos(out Point ppt);

    private void Form1_MouseDown(object sender, MouseEventArgs e)
    {
        Point p;
        GetCaretPos(out p);
        int index = this.textBox1.GetCharIndexFromPosition(p);
        this.Text = index.ToString();
    }
}

關鍵:GetCaretPos 取得插入點螢幕座標,GetCharIndexFromPosition 轉為控件內字元索引。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved