如何獲得TextBox裡游標位置

來源:互聯網
上載者:User

這個問題來自論壇。

第一反應是SelectionStart屬性,結果發現在分方向選擇內容時返回錯誤值,真正答案如下:

using
 System;

using
 System.ComponentModel;

using
 System.Windows.Forms;

using
 System.Runtime.InteropServices;

using
 System.Drawing;

namespace
 WindowsApplication5

...
{

    
public
 
partial
 
class
 Form1 : Form

    
...
{

        
public
 Form1()

        
...
{

            InitializeComponent();

        }



        [DllImport(
"
user32.dll
"
)]

        
private
 
static
 
extern
 
bool
 GetCaretPos(
out
 Point ppt);  


        
private
 
void
 Form1_Load(
object
 sender, EventArgs e)

        
...
{

            
this
.textBox1.Text 
=
 
"
jinjazz
"
;

        }



        
private
 
void
 Form1_MouseDown(
object
 sender, MouseEventArgs e)

        
...
{

           Point p;

           GetCaretPos(
out
 p);

           
int
 i
=
this
.textBox1.GetCharIndexFromPosition(p);

           
this
.Text 
=
 i.ToString();


        }



    }



}

 在zswang(偶最pf的伴水)的提醒下,上面方法存在兩個遺漏,zswang的補充如下:

1、當輸入焦點沒有在編輯框中(比如有多個輸入框),這樣游標的位置擷取並非指定。
  當然可以考慮擷取之前先Focus()一下。
2、GetCharIndexFromPosition()方法有缺陷,當游標在最後一個字元來回的時候數值不變-_-!!!得完善一下。

public
 
virtual
 
int
 GetCharIndexFromPosition(Point pt)

...
{

    
int
 lParam 
=
 NativeMethods.Util.MAKELONG(pt.X, pt.Y);

    
int
 n 
=
 (
int
) UnsafeNativeMethods.SendMessage(
new
 HandleRef(
this

base
.Handle), 
0xd7

0
, lParam); 
//
EM_CHARFROMPOS = 0xd7


    n 
=
 NativeMethods.Util.LOWORD(n);

    
if
 (n 
<
 
0
)

    
...
{

        
return
 
0
;

    }



    
string
 text 
=
 
this
.Text;

    
if
 (n 
>=
 text.Length)

    
...
{

        n 
=
 Math.Max(text.Length 
-
 
1

0
); 
//
<<<<<<<


    }



    
return
 n;

}


感謝zswang!!!

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.