如何获得TextBox里光标位置

这个问题来自论坛。

第一反应是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 Pointppt);

private void Form1_Load( object sender,EventArgse)
... {
this .textBox1.Text = " jinjazz " ;
}

private void Form1_MouseDown( object sender,MouseEventArgse)
... {
Pointp;
GetCaretPos(
out p);
int i = this .textBox1.GetCharIndexFromPosition(p);
this .Text = i.ToString();

}

}

}

在zswang(偶最pf的伴水)的提醒下,上面方法存在两个遗漏,zswang的补充如下:

1、当输入焦点没有在编辑框中(比如有多个输入框),这样光标的位置获取并非指定。
当然可以考虑获取之前先Focus()一下。
2、GetCharIndexFromPosition()方法有缺陷,当光标在最后一个字符来回的时候数值不变-_-!!!得完善一下。

public virtual int GetCharIndexFromPosition(Pointpt)
... {
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!!!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值